且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WindowsError: [错误 2] 系统找不到指定的文件

更新时间:2023-01-25 23:22:35

我怀疑您的子目录可能有问题.

I suspect that you may be having issues with subdirectories.

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

If you have a directory with files "a", "b" and subdirectory "dir" with files "sub+1" and "sub+2", the call to os.walk() will yield the following values:

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

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

When you process the second tuple, you will call rename() with 'sub+1', 'sub_1' as the arguments, when what you want is 'dir\sub+1', 'dir\sub_1'.

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

To fix this, change the loop in your code to:

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

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

which will concatenate the directory with the filename before you do anything with it.

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

I think the above is the right answer, but not quite the right reason.

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

Assuming you have a file "File+1" in the directory, os.walk() will return

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

除非你在10G304655_1"目录下,否则当你调用rename()时,文件File+1"不会可以在 current 目录中找到,因为它与 os.walk() 正在查找的目录不同.通过调用 os.path.join() 你告诉 rename 在正确的目录中查找.

Unless you are in the "10G304655_1" directory, when you call rename(), the file "File+1" will not be found in the current directory, as that is not the same as the directory os.walk() is looking in. By doing the call to os.path.join() yuo are telling rename to look in the right directory.

编辑 2

所需代码的示例可能是:

A example of the code required might be:

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