Python File Renaming

前端 未结 1 348
小鲜肉
小鲜肉 2021-01-23 22:13

I have some files in a directory,

file_IL.txt
file_IL.csv
file_NY.txt
file_NY.csv

I will have to rename them so that they get a sequence number.

相关标签:
1条回答
  • 2021-01-23 22:32

    The best approach is to store the extension and count for that extension in a dictionary.

    def __call__(self):  
    
        found = glob.glob(self.indir + '/file*')  
        length = len(found)  
        counts = {}
    
        for num in found:
            ext = num.rsplit(".",1)[-1]    # Right split to get the extension
            count = counts.get(ext,0) + 1  # get the count, or the default of 0 and add 1
            shutil.copy(num, num+'_'+'%03d' % count)   # Fill to 3 zeros
            counts[ext] = count            # Store the new count
    
    0 讨论(0)
提交回复
热议问题