Reputation:
As in the title, I am getting this error,
FileNotFoundError: [WinError 2] The system cannot find the file specified:
I am newbie in coding then, I was coding as, was done in a website called udacity, following them I wrote this code,
import os
def rename_files():
files = os.listdir(r"C:\Users\WIN8\Desktop\oop\prank")
#print(files)
saved_path = os.getcwd()
print("current working directory is" + saved_path)
os.chdir(r"C:\Users\WIN8\Desktop\oop\prank")
for file_temp in files:
os.rename(
file_temp,
file_temp.translate(str.maketrans('', '', '0123456789')))
os.chdir(saved_path)
rename_files()
now the error i am getting is
Traceback (most recent call last):
File "C:/Users/WIN8/Desktop/Tumin/First_Program/secret message.py", line 13, in <module>
rename_files()
File "C:/Users/WIN8/Desktop/Tumin/First_Program/secret message.py", line 11, in rename_files
file_temp.translate(str.maketrans('', '', '0123456789')))
FileNotFoundError: [WinError 2] The system cannot find the file specified: '16los angeles.jpg' -> 'los angeles.jpg'
Then i was also getting an error while typing file_temp.translate(None, "0123456789")
then it was saying something like, error2, one argument is needed two is declared or something. then i searched for the problem and in a thread found this code
(
file_temp,
file_temp.translate(str.maketrans('', '', '0123456789')))
but it didnt worked either.
Thanks for helping.
Upvotes: 0
Views: 13436
Reputation: 3
the problem is indent at os.chdir in loops it must be outside the loop
import os
def rename_files():
files = os.listdir(r"C:\Users\WIN8\Desktop\oop\prank")
#print(files)
saved_path = os.getcwd()
print("current working directory is" + saved_path)
os.chdir(r"C:\Users\WIN8\Desktop\oop\prank")
for file_temp in files:
os.rename(
file_temp,
file_temp.translate(str.maketrans('', '', '0123456789')))
os.chdir(saved_path)
rename_files()
Upvotes: 0
Reputation: 73
Try this:
import os
def rename_files():
fileslst = os.listdir(r"/Users/sachin/MACBOOK/prank")
print(fileslst)
saved_path = os.getcwd()
for filename in fileslst:
os.rename(filename, filename.strip("0123456789"))
os.chdir(saved_path)
rename_files()
Pls. note:
1.Replace the 'prank' folder's path (with folder location on your PC)2.It'd be a good idea to make prank as your current working dir(cwd)
OR put the images in your cwd (this may be the cause of your ^ error)
The above code is working.
It'll first print the original names of the files in the folder.
Then, once the entire code is run, it'll rename the files in the same folder without any output in the console. You can visit the folder and see that none of the filenames have any digits.
p.s. if you are not sure of what is currently set as your WD use the following code:
import os
print('Current working directory path:',os.getcwd())
Upvotes: 1