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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With