当前位置: 移动技术网 > IT编程>脚本编程>Python > python解决方案:WindowsError: [Error 2]

python解决方案:WindowsError: [Error 2]

2017年12月12日  | 移动技术网IT编程  | 我要评论

广州公交路线查询,碎发,繁体

使用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可以重命名任意文件。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网