手机
当前位置:查字典教程网 >脚本专栏 >python >python解决方案:WindowsError: [Error 2]
python解决方案:WindowsError: [Error 2]
摘要:使用Python的rename()函数重命名文件时出现问题,提示WindowsError:[Error2]错误,最初代码如下:defrena...

使用Python的rename()函数重命名文件时出现问题,提示 WindowsError: [Error 2] 错误,最初代码如下:

def renameFile(filename): filePre = "D:FileDemoPythonpt.py" os.rename(filePre, filename) print os.listdir(filePre) if __name__ == '__main__': fileNew = "D:FileDemoPythonTest.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:FileDemoPythonPT.py" fileNew = "D:FileDemoPythonTest.txt" renameF(filePre, fileNew)

代码非常简洁,通过修改filePre,fileNew可以重命名任意文件。

【python解决方案:WindowsError: [Error 2]】相关文章:

python迭代器的使用方法实例

python中文乱码的解决方法

SublimeText 2编译python出错的解决方法(The system cannot find the file specified)

python调用windows api锁定计算机示例

python连接sql server乱码的解决方法

python解析文件示例

python列表去重的二种方法

python 测试实现方法

python使用递归解决全排列数字示例

python解析json实例方法

精品推荐
分类导航