[英]FileNotFoundError: [WinError 2] The system cannot find the file specified:
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.对不起,如果这是一个愚蠢的问题,我是编码新手。
As written you're looking for a file named 0.jpg
in the working directory.正如所写,您正在工作目录中查找名为
0.jpg
的文件。 You want to be looking in the directory you pass in.您想查看您传入的目录。
So instead do:所以改为:
os.rename(os.path.join(directory,name),
os.path.join(directory,'0'+name))
Agreeing with Bernie's answer that "filename" is used to mean the full/absolute path name .同意 Bernie 的回答,即“文件名”用于表示完整/绝对路径名。 The below will also work.
以下也将起作用。
os.rename((directory+name),(directory+'0'+name))
You cannot use absolute path unless your terminal is in that directory.除非您的终端在该目录中,否则您不能使用绝对路径。 Hence you can do as following:
因此,您可以执行以下操作:
import os
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.