David Jaimes
David Jaimes

Reputation: 1

Using Python to rename a group of files using an array

So I have a group of screenshots in a folder on my desktop. I want to rename them using an array of the names I want them to have. So far I am able to get my code to pull the names I want to replace and put them in an array. Then when I try to replace the name using the commented portion of code I loose the files. They disappear and I have no idea where they went. Here is my code:

import os       
import sys
import glob
name = ["zero", "It", "Has","Worked"]

print name
print len(name) 
path = "/Users/davidjaimes/Desktop/Test"
dirs = os.listdir(path)
file_list = []

for file in dirs: 
    file_list.append(file)
print file_list


#for item in os.listdir(path):
#    prevName = os.path.join(path, item)
#    newName = name[1]
#   os.rename(prevName, newName)

Upvotes: 0

Views: 562

Answers (1)

Scott Hunter
Scott Hunter

Reputation: 49883

Notice that, to open the files, you needed to append path to the name. In order for the renamed file to stay in the same directory, you must do the same w/ the new name, otherwise they get moved to the current directory (most likely the one you started the program from).

Worse, since you use name[1] for the new name for every file, you are naming all of the files w/ the same name.

Upvotes: 1

Related Questions