繁体   English   中英

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

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

我遇到了这个代码的问题。 我正在尝试重命名文件夹中的所有文件名,以便它们不再包含+'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))

我怀疑您可能遇到子目录问题。

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

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

当你处理第二个元组时,你将调用rename()其中'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() ,在当前目录中找不到文件“ File+1 ”,因为这与os.walk()查找的目录不同通过调用os.path.join() yuo告诉rename查找正确的目录。

编辑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

您正在使用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('+','_'))

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM