简体   繁体   中英

Renaming files in Python: No such file or directory

If I try to rename files in a directory, for some reason I get an error. I think the problem may be that I have not inserted the directory in the proper format ?

Additional info: python 2 & linux machine

OSError: [Errno 2] No such file or directory

Though it prints the directories content just fine. What am I doing wrong?

import os

for i in os.listdir("/home/fanna/Videos/strange"):
    #print str(i)
    os.rename(i, i[:-17])

os.rename() is expecting the full path to the file you want to rename. os.listdir only returns the filenames in the directory. Try this

import os
baseDir = "/home/fanna/Videos/strange/"
for i in os.listdir( baseDir ):
    os.rename( baseDir + i, baseDir + i[:-17] )

Suppose there is a file /home/fanna/Videos/strange/name_of_some_video_file.avi , and you're running the script from /home/fanna .

i is name_of_some_video_file.avi (the name of the file, not including the full path to it). So when you run

os.rename(i, i[:-17])

you're saying

os.rename("name_of_some_video_file.avi", "name_of_some_video_file.avi"[:-17])

Python has no idea that these files came from /home/fanna/Videos/strange . It resolves them against the currrent working directory, so it's looking for /home/fanna/name_of_some_video_file.avi .

I'm a little late but the reason it happens is that os.listdir only lists the items inside that directory, but the working directory remains the location where the python script is located.

So to fix the issue add:

os.chdir(your_directory_here)

just before the for loop where your_directory_here is the directory you used for os.listdir .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM