简体   繁体   中英

Rename all files in folder with Python

Good afternoon. I have 500 pictures (*.jpg) with bad filenames. I want to rename all the files to 01, 02, and so on. Where did I make a mistake?

i = 0
path="D:/data"
for filename in os.listdir(path):
      my_dest ="0" + str(i) + ".jpg"
      my_source = path + filename
      # rename all the files
      os.rename(my_source, my_dest)
      i += 1

path does not end with / , so for example, if there was a file named "example.jpg", my_source would be "D:/dataexample.jpg" . You should look into using os.path.join instead.

Additionally, my_dest = my_dest doesn't do anything, and os.rename will error when you're specifying the full path for the source and only the filename for the destination. You should specify either the full path for both or only the filename for both if you only intend to rename the file without moving it and it's in the current working directory.

You should also look into enumerate and string formatting .

You can use the os.path.splitext to get the filename + extension and os.path.dirname to get the directory of filename. This may help you to build the destination. Use os.path.join to merge the directory and filename of the destination

Harmon758's answer already pinpointed all the errors and improvements that you can do, so I am only putting them all together. You should:

  • Use os.path.join for creating the filenames without caring for trailing '/',

  • Use enumeration instead of counting the files with an extra counter variable,

  • Use string format for achieving the naming you described, instead of making all names start with a zero. In the code below, it generates names, left padded with zeros, of length 3. You can change that to the desired length (after the '>').

    import os

    path="D:/data"
    for itr, filename in enumerate(os.listdir(path)):
        my_source = os.path.join(path, filename)
        my_dest = os.path.join(path, "{:0>3}.jpg".format(itr + 1))
        # Rename all the files
        os.rename(my_source, my_dest)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM