手机
当前位置:查字典教程网 >脚本专栏 >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]】相关文章:

rhythmbox中文名乱码问题解决方法

python中文乱码的解决方法

vc6编写python扩展的方法分享

python字符串加密解密的三种方法分享(base64 win32com)

python解析json实例方法

Python实现全局变量的两个解决方法

Python 解析XML文件

python列表去重的二种方法

python 测试实现方法

python读取注册表中值的方法

精品推荐
分类导航