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中多个装饰器的调用顺序详解

python中多个装饰器的调用顺序详解

前言 一般情况下,在函数中可以使用一个装饰器,但是有时也会有两个或两个以上的装饰器。多个装饰器装饰的顺序是从里到外(就近原则),而调用的顺序是从外到里(就远原则)。 原代码 执行结果...

python中django框架通过正则搜索页面上email地址的方法

本文实例讲述了python中django框架通过正则搜索页面上email地址的方法。分享给大家供大家参考。具体实现方法如下: import re from django.shortc...

Python2和Python3的共存和切换使用

Python2和Python3的共存和切换使用

  从python2到python3,这两个版本可以说是从语法、编码等多个方面上都有很大的差别。为了不带入过多的累赘,Python 3.0在设计的时候没有考虑向下相容,也就是说许多针对早...

Python、PyCharm安装及使用方法(Mac版)详解

Python、PyCharm安装及使用方法(Mac版)详解

上周跟朋友喝咖啡时聊起我想学Python,她恰好也有这个打算,顺便推荐了一本书《编程小白的第1本Python入门书》,我推送到Kindle后,随手翻看了下,用语平实,简洁易懂。 之前在R...

python lambda表达式在sort函数中的使用详解

1.lambda表达式一般用法 语法: lamda argument:expression example: add = lambda x, y: x+y print(add(10,...