Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming files in Python: No such file or directory

Tags:

python

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])
like image 408
Fanna1119 Avatar asked Dec 03 '22 23:12

Fanna1119


2 Answers

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] )
like image 109
CDspace Avatar answered Dec 26 '22 21:12

CDspace


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.

like image 44
Chris Martin Avatar answered Dec 26 '22 22:12

Chris Martin