Skip to content Skip to sidebar Skip to footer

Os.rename Fails To Rename Files For A Certain Directory

This is my first time using stack overflow so sorry if i make a mistake. When trying to run this code it will execute fine and give me my properly renamed files. import os a = 0 na

Solution 1:

The problem is that for other directories, you are getting the directory contents properly but when you try and rename the contents simply by using filenames, the program in fact looks it its own directory, and being unable to find the file, throws an error. Instead you should do something as follows:

os.rename('\some\folder\elsewhere\filename.txt', '\some\folder\elsewhere\filename2.txt')

Or, you can also do the following:

directory = '\some\folder\elsewhere'os.rename(os.path.join(directory, 'filename.txt'), os.path.join(directory, 'filename2.txt'))

Or, you can also change your working directory as follows:

os.chdir('\some\folder\elsewhere')

An then simply call the os.rename method as if you are in the desired directory os.rename('filename.txt', 'filenam2.txt')

Solution 2:

If you use os.listdir(path), you also have to provide the path in the rename: os.rename(path+filename,path+new_name).

Other option is to use os.chdir(desired_path). With this, your os.rename is fine.

Post a Comment for "Os.rename Fails To Rename Files For A Certain Directory"