1

我在一个目录中有一些文件,

文件_IL.txt文件_IL.csv 文件
_NY.txt
文件
_NY.csv

我将不得不重命名它们,以便它们获得序列号。例如,

文件_IL.txt_001文件_IL.csv_001 文件
_NY.txt_002
文件
_NY.csv_002

我编写了以下 Python 代码

def __init__(self):  

    self.indir = "C:\Files"  



def __call__(self):  

    found = glob.glob(self.indir + '/file*')  

    length = len(glob.glob(self.indir + '/file*'))  
    print length  
    count = 000  

    for num in (glob.glob(self.indir + '/file*')):  
        count = count + 1  
        count = str(count)  
        print count  
        shutil.copy(num, num+'_'+count)  
        print num  
        count = int(count)  

但这给了我如下结果,

文件_IL.txt_001文件_IL.csv_002 文件
_NY.txt_003
文件
_NY.csv_004

有人可以帮我修改上面的 Python 脚本以符合我的要求吗?我是 Python 新手,我不确定如何实现它。

4

1 回答 1

3

最好的方法是将扩展名和该扩展名的计数存储在字典中。

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
于 2013-10-27T22:50:40.870 回答