Python FileNotFoundError: [WinError 2] 系统找不到指定的文件:
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35443278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
FileNotFoundError: [WinError 2] The system cannot find the file specified:
提问by Bracktus
import os
def rename(directory):
for name in os.listdir(directory):
print(name)
os.rename(name,"0"+name)
path = input("Enter the file path")
rename(path)
I want to rename every file in a certain directory so that it adds a 0 to the beginning of the file name, however when I try to run the code it comes up with this error:
我想重命名某个目录中的每个文件,以便在文件名的开头添加 0,但是当我尝试运行代码时,它出现了这个错误:
(FileNotFoundError: [WinError 2] The system cannot find the file specified: '0.jpg' -> '00.jpg')
(FileNotFoundError: [WinError 2] 系统找不到指定的文件: '0.jpg' -> '00.jpg')
I'm sure that there is a file in there named 0.jpg and i'm not sure what the problem is.
我确定那里有一个名为 0.jpg 的文件,但我不确定问题是什么。
Sorry if this is a stupid question i'm new to coding.
对不起,如果这是一个愚蠢的问题,我是编码新手。
采纳答案by mechanical_meat
As written you're looking for a file named 0.jpg
in the working directory. You want to be looking in the directory you pass in.
正如所写,您正在寻找一个0.jpg
在工作目录中命名的文件。您想查看您传入的目录。
So instead do:
所以改为:
os.rename(os.path.join(directory,name),
os.path.join(directory,'0'+name))
回答by Tad
Agreeing with Bernie's answer that "filename" is used to mean the full/absolute path name . The below will also work.
同意 Bernie 的回答,即“文件名”用于表示完整/绝对路径名。以下也将起作用。
os.rename((directory+name),(directory+'0'+name))
回答by Aravindh nivas.M
You cannot use absolute path unless your terminal is in that directory. Hence you can do as following:
除非您的终端在该目录中,否则您不能使用绝对路径。因此,您可以执行以下操作:
def rename(directory):
os.chdir(directory) # Changing to the directory you specified.
for name in os.listdir(directory):
print(name)
os.rename(name,"0"+name)