Python新手问题。
我正在尝试重命名目录中的文件...
路径的值为
C:\tempdir\1\0cd3a8asdsdfasfasdsgvsdfc1.pdf
而 newfile 的值为
C:\tempdir\1\newfilename.pdf
origfile = path
newfile = path.split("\\")
newfile = newfile[0]+"\\"+newfile[1]+"\\"+newfile[2]+"\\"+text+".pdf"
os.rename(path, newfile)
print origfile
print newfile
我收到以下错误...
os.rename(path, newfile)
WindowsError: [Error 3] The system cannot find the path specified
我知道目录和文件很好,因为我可以在上面调用 os.stats() 。我已更改为 newfile 的值以仅包含新文件名,但收到相同的错误(在阅读有关 rename() 的 python 文档后)
我导入的库是......
import sys
import os
import string
from os import path
import re
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from cStringIO import StringIO
我已经阅读了有关此主题的一些其他主题 - 与绝对路径与相对路径有关。显然,我的意图是使用绝对路径。我的变量是字符串变量,换句话说...
origfile = "C:\tempdir\1\0cd3a8asdsdfasfasdsgvsdfc1.pdf"
够了吗?或者我应该使用其他一些声明来告诉 python 这是一条路径?
最佳答案
您可以尝试以下方法吗?您可能会发现使用不同的 API 时重命名会更容易。
import pathlib
parent = pathlib.Path('C:/') / 'tempdir' / '1'
old = parent / '0cd3a8asdsdfasfasdsgvsdfc1.pdf'
new = parent / 'newfilename.pdf'
old.rename(new)
使用 pathlib
模块可以使跨平台方式处理路径变得更加简单。
关于python - 错误3 : Renaming files in python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39729400/