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

已经是深秋了,森林里那一望无际的林木都已光秃,让褐色的苔掩住它身上的皱纹。无情的秋天剥下了它们美丽的衣裳,它们只好枯秃地站在那里。

使用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解决方案:WindowsError: [Error 2]就介绍到这了。芷兰知香,怀情仰望天空,为青春呐喊;牡丹芬芳,抱爱脚踏实地,为年轻喝彩。更多相关python解决方案:WindowsError: [Error 2]内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!

您可能有感兴趣的文章
Python自动化运维-使用Python脚本监控华为AR路由器关键路由变化

Python自动化运维-netmiko模块设备自动发现

Python自动化运维—netmiko模块连接并配置华为交换机

Python自动化运维-利用Python-netmiko模块备份设备配置

Python自动化运维-Paramiko模块和堡垒机实战