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

yipeiwu_com5年前Python基础

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

相关文章

对pandas中两种数据类型Series和DataFrame的区别详解

对pandas中两种数据类型Series和DataFrame的区别详解

1. Series相当于数组numpy.array类似 s1=pd.Series([1,2,4,6,7,2]) s2=pd.Series([4,3,1,57,8],index=['a...

python如何在循环引用中管理内存

python中通过引用计数来回收垃圾对象,在某些环形数据结构(树,图……),存在对象间的循环引用,比如树的父节点引用子节点,子节点同时引用父节点,此时通过del掉引用父子节点,两个对象不...

Django admin禁用编辑链接和添加删除操作详解

禁用admin中models的编辑链接和添加删除按钮 方法如下: class MyModelAdmin(models.ModelAdmin): ... List_display_...

python mac下安装虚拟环境的图文教程

python mac下安装虚拟环境的图文教程

Mac 下 Flask 框架 workon命令找不到 ---- 最终解决方案(详解具体实现操作过程中遇到的坑)2018年08月17日 00:02:05Jasonmes阅读数:622 Ma...

详解Python 2.6 升级至 Python 2.7 的实践心得

前言 CentOS 6.8 安装 Python 2.7.13,因为软件版本上的需求所以考虑将 Python 升级至 2.7.13,加上生产环境还是以 RHEL 6 为主,互联网自动化运...