user3458913
user3458913

Reputation: 3

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
name_target = raw_input("input the prefix of the files you want enumerated")
for filename in os.listdir("."):
    if filename.startswith(name_target):
        a = int(a) + 1
        a = str(a)
        no = filename.__len__() - 4
        os.rename(filename, filename[:no] + a + '.txt')

Now this is fine as long as the script exists in the same folder as the files are. But I want to be able to use this script with files which are not in the same folder.

I have found that os.listdir('\some\folder\elsewhere') works fine for other directories but when it comes to renaming them withos.rename the code breaks giving me the message:

Traceback (most recent call last):
  File "<string>", line 244, in run_nodebug
  File "C:\Users\guy\Desktop\otherfolder\renaming_script.py", line 10, in <module>
    os.rename(filename, filename[:no] + a + '.txt')
WindowsError: [Error 2] The system cannot find the file specified`

I have no idea what is wrong here please help me.

Upvotes: 0

Views: 11754

Answers (2)

sshashank124
sshashank124

Reputation: 32189

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')

Upvotes: 1

DavidRguez
DavidRguez

Reputation: 1110

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.

Upvotes: 0

Related Questions