广州公交路线查询,碎发,繁体
使用Python的rename()函数重命名文件时出现问题,提示 WindowsError: [Error 2] 错误,最初代码如下:
def renameFile(filename): filePre = "D:\\FileDemo\\Python\\pt.py" os.rename(filePre, filename) print os.listdir(filePre) if __name__ == '__main__': fileNew = "D:\\FileDemo\\Python\\Test.py" renameFile(fileNew)
后来经过反复尝试,问题解决~
rename之前要先用chdir()函数进入到目标文件所在的路径,告诉python编译器要重命名的文件在哪儿,然后才可以修改;
Python不是可怕的终结者,她其实很幼小,自己找不到文件,需要我们详细又耐心的告诉她该去哪儿找~ 路径通过 os.path.dirname()函数获得:
import os from nt import chdir def renameF(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可以重命名任意文件。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Python爬虫:Request Payload和Form Data的简单区别说明
浅谈Python中threading join和setDaemon用法及区别说明
Python3-异步进程回调函数(callback())介绍
python继承threading.Thread实现有返回值的子类实例
Python中使用threading.Event协调线程的运行详解
网友评论