FileNotFoundError: [WinError 2] The system cannot find the file specified:
Question:
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:
(FileNotFoundError: [WinError 2] The system cannot find the file specified: ‘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.
Answers:
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.
So instead do:
os.rename(os.path.join(directory,name),
os.path.join(directory,'0'+name))
I am agreeing with mechanical_meat’s answer that "filename" is used to mean the full/absolute path name. The below will also work.
os.rename((directory + name), (directory + '0' + name))
You cannot use an absolute path, unless your terminal is in that directory.
Hence, you can do as in the 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)
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:
(FileNotFoundError: [WinError 2] The system cannot find the file specified: ‘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.
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.
So instead do:
os.rename(os.path.join(directory,name),
os.path.join(directory,'0'+name))
I am agreeing with mechanical_meat’s answer that "filename" is used to mean the full/absolute path name. The below will also work.
os.rename((directory + name), (directory + '0' + name))
You cannot use an absolute path, unless your terminal is in that directory.
Hence, you can do as in the 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)