I have written a script to rename a file
import os
path = "C:\\Users\\A\\Downloads\\Documents\\"
for x in os.listdir(path):
if x.startswith('i'):
os.rename(x,"Information brochure")
When the python file is in a different directory than the path I get a file not found error
Traceback (most recent call last):
File "C:\Users\A\Desktop\script.py", line 5, in <module>
os.rename(x,"Information brochure")
FileNotFoundError: [WinError 2] The system cannot find the file specified:'ib.pdf'-> 'Information brochure'
But if I copy the python file to the path location it works fine
import os
for x in os.listdir('.'):
if x.startswith('i'):
os.rename(x,"Information brochure")
What is the problem?
asked May 26, 2014 at 3:35
honeysingh
691 gold badge2 silver badges8 bronze badges
-
Are you sure the path is correct?lily– lily2014年05月26日 03:38:26 +00:00Commented May 26, 2014 at 3:38
-
os.chdir(path) workedhoneysingh– honeysingh2014年05月26日 03:44:24 +00:00Commented May 26, 2014 at 3:44
2 Answers 2
Your variable x is currently only the filename relative to path. It's what os.listdir(path) outputs. As a result, you need to prepend path to x using os.path.join(path,x).
import os
path = "C:\\Users\\A\\Downloads\\Documents\\" #os.path.join for cross-platform-ness
for x in os.listdir(path):
if x.startswith('i'): # x, here is the filename. That's why it starts with i.
os.rename(os.path.join(path,x),os.path.join(path,"Information brochure"))
answered May 26, 2014 at 3:40
sihrc
2,8782 gold badges26 silver badges43 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
R Sahu
I would suggest using
os.rename(os.path.join(path,x),os.path.join(path,"Information brochure"))honeysingh
Yes
os.rename(os.path.join(path,x),os.path.join(path,"Information brochure")) worked.I dont know what os.rename(os.path.join(path,x),"Information brochure") did but it deleted the file from the directorysihrc
@honeysingh Since you didn't give it the absolute path, it probably just moved the file to the current directory.
honeysingh
@sihrc yes it moved the file to current directory
The x variable has the name of the file but not the full path to the file. Use this:
os.rename(path + "\\" + x, "Information brochure")
1 Comment
jspurim
Actually, now I see sihrc, answer is better as it is more portable.
lang-py