【问题标题】:Python - WindowsError: [Error 2] The system cannot find the file specifiedPython - WindowsError: [错误 2] 系统找不到指定的文件
【发布时间】:2016-01-15 22:07:38
【问题描述】:

我有一个装满 pdf 文件的文件夹。我正在尝试从文件名中删除所有空格并用下划线替换它们。到目前为止,这是我所拥有的:

import os, sys

folder = path to folder
FileList = os.listdir(folder)

for files in FileList:
    if ' ' in files:
        NewName = files.replace(" ", "_")
        os.rename(files, NewName)

当我运行此脚本时,我收到以下错误:

WindowsError: [Error 2] The system cannot find the file specified

我猜有一个非常简单的解决方法,但我已经四处寻找,找不到适合我生活的解决方案。

感谢您的帮助!

【问题讨论】:

  • cwd/folder/filecwd/file 中找不到。

标签: python filenames


【解决方案1】:

...

os.rename(os.path.join(folder, files), os.path.join(folder, NewName))

【讨论】:

    【解决方案2】:

    只需将您的目录更改为必须重命名文件的目录,然后按照您的代码进行操作即可。

    使用:os.chdir("destinationFolder")

    【讨论】:

      【解决方案3】:

      我为我的案例找到了一个简单的解决方案。我想重命名文件并不断收到 WindowsError:[错误 2]。只需使用

      更改当前目录
      os.chdir(currdir)
      

      然后不尝试使用完整路径就可以了。这是脚本的相关行

      if(os.path.exists(wd)) == 0:
      print(wd+" DOES NOT EXIST!!")
      sys.exit()
      
      directories = [x[0] for x in os.walk(wd)]
      ld = len(directories)
      dsorted = sorted(directories)
      print(dsorted)
      
      for num in range(1,ld):
          currdir = dsorted[num]
          print("Working on Directory  "+currdir)
          os.chdir(currdir)
          filenames = next(os.walk(currdir))[2]
          l = len(filenames)
      
          for num in range(0,l):
      
              name = filenames[num]
              print("Present file  "+name)
              modtime = os.path.getmtime(name);print(modtime)
              moddate =datetime.datetime.fromtimestamp(modtime).strftime('%Y %m %d')
              moddate = moddate.replace(" ", "")
              print(moddate)
      
              namesplit = name.split(".")
      
              base = namesplit[0]
              newbase = base+"_"+moddate   
              newname = newbase+"."+namesplit[1]
              print(newname)       
      
              os.rename(name,newname)
              input()
      

      【讨论】:

        【解决方案4】:

        您重命名当前目录中的文件,但读取folder。您需要添加到os.rename文件夹路径或开头os.chdir(folder)然后只需使用os.listdir()os.rename

        【讨论】:

          猜你喜欢
          • 2011-07-16
          • 1970-01-01
          • 2014-04-12
          • 2016-08-17
          • 2018-10-21
          • 2018-03-26
          • 2017-05-02
          • 1970-01-01
          • 2014-02-13
          相关资源
          最近更新 更多