使用Python的rename()函数重命名文件时出现问题,提示 WindowsError: [Error 2] 错误,最初代码如下:
defrenameFile(filename):filePRe="D:\\FileDemo\\Python\\pt.py"os.rename(filePre, filename)printos.listdir(filePre)if__name__=='__main__':
fileNew="D:\\FileDemo\\Python\\Test.py"renameFile(fileNew)
后来经过反复尝试,问题解决~
rename之前要先用chdir()函数进入到目标文件所在的路径,告诉python编译器要重命名的文件在哪儿,然后才可以修改;
Python不是可怕的终结者,她其实很幼小,自己找不到文件,需要我们详细又耐心的告诉她该去哪儿找~ 路径通过 os.path.dirname()函数获得:
importosfromntimportchdirdefrenameF(preName, newName):
chdir(os.path.dirname(preName))
os.rename(preName, newName)if__name__=='__main__':
filePre="D:\FileDemo\Python\PT.py"fileNew="D:\FileDemo\Python\Test.txt"renameF(filePre, fileNew)
代码非常简洁,通过修改filePre,fileNew可以重命名任意文件。