13

我有这个代码的问题。我正在尝试重命名文件夹中的所有文件名,以便它们不再包含+'s在其中!这已经工作了很多次,但突然我得到了错误:

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

第 26 行是代码的最后一行。

有谁知道为什么会这样?我只是向某人保证我可以在 5 分钟内完成这项工作,因为我有一个代码!可惜没用!!

import os, glob, sys
folder = "C:\\Documents and Settings\\DuffA\\Bureaublad\\Johan\\10G304655_1"

for root, dirs, filenames in os.walk(folder):
    for filename in filenames:
        filename = os.path.join(root, filename)
old = "+"
new = "_"
for root, dirs, filenames in os.walk(folder):
    for filename in filenames:
        if old in filename:
            print (filename)
            os.rename(filename, filename.replace(old,new))
4

2 回答 2

12

我怀疑您可能对子目录有问题。

如果您有一个包含文件“ ”、“ ”的目录和包含文件a“ ”和“ b”的子目录“ ”,则调用将产生以下值:dirsub+1sub+2os.walk()

(('.',), ('dir',), ('a', 'b'))
(('dir',), (,), ('sub+1', 'sub+2'))

当您处理第二个元组时,您将调用rename()with'sub+1', 'sub_1'作为参数,而您想要的是'dir\sub+1', 'dir\sub_1'.

要解决此问题,请将代码中的循环更改为:

for root, dirs, filenames in os.walk(folder):
    for filename in filenames:           
        filename = os.path.join(root, filename)
        ... process file here

在您对其进行任何操作之前,它将将该目录与文件名连接起来。

编辑:

我认为以上是正确的答案,但不是完全正确的理由。

假设您File+1在目录中有一个文件“”,os.walk()将返回

("C:/Documents and Settings/DuffA/Bureaublad/Johan/10G304655_1/", (,), ("File+1",))

除非您在 " 10G304655_1" 目录中,否则当您调用 时,将不会在当前目录中找到rename()文件 " ",因为这与正在查找的目录不同。通过对yuo 的调用告诉 rename 要查找在正确的目录中。File+1os.walk()os.path.join()

编辑 2

所需代码的示例可能是:

import os

# Use a raw string, to reduce errors with \ characters.
folder = r"C:\Documents and Settings\DuffA\Bureaublad\Johan\10G304655_1"

old = '+'
new = '_'

for root, dirs, filenames in os.walk(folder):
 for filename in filenames:
    if old in filename: # If a '+' in the filename
      filename = os.path.join(root, filename) # Get the absolute path to the file.
      print (filename)
      os.rename(filename, filename.replace(old,new)) # Rename the file
于 2011-03-16T12:34:47.990 回答
4

splitext用于确定要重命名的源文件名:

filename_split = os.path.splitext(filename) # filename and extensionname (extension in [1])
filename_zero = filename_split[0]#
...
os.rename(filename_zero, filename_zero.replace('+','_'))

如果您遇到带有扩展名的文件,显然,尝试重命名不带扩展名的文件名将导致“找不到文件”错误。

于 2011-03-16T10:45:45.683 回答