1

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?

2
  • Are you sure the path is correct? Commented May 26, 2014 at 3:38
  • os.chdir(path) worked Commented May 26, 2014 at 3:44

2 Answers 2

3

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"))
Sign up to request clarification or add additional context in comments.

4 Comments

I would suggest using os.rename(os.path.join(path,x),os.path.join(path,"Information brochure"))
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 directory
@honeysingh Since you didn't give it the absolute path, it probably just moved the file to the current directory.
@sihrc yes it moved the file to current directory
0

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

Actually, now I see sihrc, answer is better as it is more portable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.