我遇到了这个代码的问题.我正在尝试重命名文件夹中的所有文件名,以便它们不再存在+'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))
Run Code Online (Sandbox Code Playgroud)
Sim*_*lan 11
我怀疑您可能遇到子目录问题.
如果你有一个带有文件" a"," b"和子目录" dir" 的目录,其中包含文件" sub+1"和" sub+2",调用os.walk()将产生以下值:
(('.',), ('dir',), ('a', 'b'))
(('dir',), (,), ('sub+1', 'sub+2'))
Run Code Online (Sandbox Code Playgroud)
当你处理第二元组,你会调用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
Run Code Online (Sandbox Code Playgroud)
在您对目录执行任何操作之前,它将使用文件名连接目录.
编辑:
我认为以上是正确的答案,但不是正确的理由.
假设您File+1在目录中有一个文件" ",os.walk()将返回
("C:/Documents and Settings/DuffA/Bureaublad/Johan/10G304655_1/", (,), ("File+1",))
Run Code Online (Sandbox Code Playgroud)
除非你在" 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
83818 次 |
| 最近记录: |