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

yipeiwu_com6年前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可以重命名任意文件。

相关文章

浅谈Python实现2种文件复制的方法

本文实例主要实现Python中的文件复制操作,有两种方法,具体实现代码如下所示: #coding:utf-8 # 方法1:使用read()和write()模拟实现文件拷贝...

python tkinter基本属性详解

python tkinter基本属性详解

1.外形尺寸 尺寸单位:只用默认的像素或者其他字符类的值!,不要用英寸毫米之类的内容。 btn = tkinter.Button(root,text = '按钮') # 设置按钮尺寸...

对Python中内置异常层次结构详解

如下所示: BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exceptio...

python字符串查找函数的用法详解

python字符串查找函数的用法详解

python字符串查找函数的使用 打开Python开发工具IDLE,新建‘findstr.py'文件,并写代码如下: s ='/ab/bx,.s' print (s.find('/x...

Python实现在tkinter中使用matplotlib绘制图形的方法示例

Python实现在tkinter中使用matplotlib绘制图形的方法示例

本文实例讲述了Python实现在tkinter中使用matplotlib绘制图形的方法。分享给大家供大家参考,具体如下: 一. 代码: # coding=utf-8 import s...