简体   繁体   中英

How to efficiently rename file names using Python?

I am trying to rename files based on a ;;;separated values.

example list is

name1;;;name_1
name2;;;name_2
name3;;;name_3

And in the directory I have files such as name_1.txt , name_2.txt and so on.

below is my code.

import os
import sys

#Usage: python rename.py rename.lst directory

r_lst = sys.argv[1]
directory = sys.argv[2]

with open(r_lst) as rfile:
    remove_list = rfile.readlines()

remove_list = [x.strip() for x in remove_list]

for item in remove_list:
    A_Column = item.split(";;;")[0]
    B_Column = item.split(";;;")[1]

    for filename in os.listdir(directory):
        basename = filename.split(".")[0]
        if basename == B_Column:
            new_name = A_Column + "." + filename.split(".")[1]
            os.rename(directory+filename, directory+new_name)

My code works on renaming the files to their correct names. However, how do I make this program more efficient? It iterates over the remove_list then within that iteration it also iterates over files in the directory.

Can I make this program more efficient?

Instead of going through each file in the directory, you could use glob with B_Column+".*" to get only those that you're interested in.

import glob
filesmatchingpattern = glob.glob(B_Column+".*")

Also note that your code may misbehave for multi-dotted file names such as name1.file.txt , which IMHO will become name_1.file instead of name_1.file.txt .

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