ErrorMaster
ErrorMaster

Reputation: 150

How does one rename multiple files using python?

I have lots of programming experience but this is my first python script. I am trying to add the prefix "00" to all the files in a specific folder. First I read the names of all the files and save them in an array. Then I sort through the array and add the prefix "00" then use the os.rename function but somewhere along the way I've messed up something.

import sys, os

file_list = []

for file in os.listdir(sys.argv[1]):
    file_list.append(file)

 for i in file_list:
    file_list[i] = prevName
    newName = '00' + file_list[i]
    os.rename(prevName, newName)

I have a .py file in the folder with all the files I want to rename. The .py file contains the script above. When i double click the .py file a cmd window flashes and disappears and none of the file names have been changed. Any help would be appreciated, sorry if this is a very obvious mistake, my python level is quite n00b at the moment.

Upvotes: 1

Views: 936

Answers (3)

Vikas Ojha
Vikas Ojha

Reputation: 6950

In addition to the answer by @Padraic, also make following changes to your code.

import sys, os

file_list = []

for f in os.listdir(sys.argv[1]):
    file_list.append(f)

for i in range(len(file_list)):
    prevName = file_list[i]
    if prevName != 'stackoverflow.py':  # Mention .py file so that it doesnt get renamed
        newName = '00' + file_list[i]
        os.rename(prevName, newName)

Upvotes: 3

Padraic Cunningham
Padraic Cunningham

Reputation: 180401

Your code errors because you provide no args so sys.argv[1] would give an IndexError, you would need to call the script with the dir name from a cmd prompt not double click it:

python your_script directory <- argv[1]

Or change the code and specify the path, you also need to join the path to the filename.

path = "full_path"
for f in os.listdir(path):
    curr,new = os.path.join(path,f), os.path.join(path,"00{}".format(f))
    os.rename(curr,new)

os.listdir returns a list so just iterate over that, you don't need to create a list and append to it.

for i in file_list: would also make each i a filename not an index so that would cause another error but as above you don't need to do it anyway.

Upvotes: 1

DeepSpace
DeepSpace

Reputation: 81594

  1. Check your indentation. The second for loop is not indented correctly.
  2. for i in file_list: file_list[i] = prevName

    You are not iterating correctly. for loops in Python are like foreach loops you may know from other programming languages. i in for i in file_list actually gives you the list's elements, so you should be doing for i in range(len(file_list)): file_list[i] = ......

    although it is not very pythonic nor generally a good idea to modify the collection that you're currently iterating over.

Upvotes: 1

Related Questions