Renaming Files In Python: No Such File Or Directory
Solution 1:
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 inos.listdir( baseDir ):
os.rename( baseDir + i, baseDir + i[:-17] )
Solution 2:
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
.
Solution 3:
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
.
Post a Comment for "Renaming Files In Python: No Such File Or Directory"