0

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

文件_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(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

这有时有效,但有时会引发如下结果,

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

我想要的是相同类型的文件,即使它们具有不同的扩展名以具有相同的计数。我现在有点迷路了,有人可以帮我吗?

4

3 回答 3

1

的输出glob.glob()是无序的。如果您希望文件名按字典顺序编号,请对文件名进行排序:

for num in sorted(found):
于 2013-10-28T02:18:01.087 回答
0

也许这会帮助你:

a=["file_IL.txt", "file_IL.csv","file_NY.txt","file_NY.csv"]
#split by dot
b = sorted([i.split('.') for i in a])

i=0
c=1

#loop through b
while i<len(b)-1:
    #start at the current index (i)
    for j in range(i, len(b)):
        #Check if file name of the current element (b[j][0]) is equal to 
        #the file name that you started with (b[i][0]).
        #If so, rename the file, else break
        if b[i][0]==b[j][0]:
            print "%s.%s%03d"%(b[j][0], b[j][1], c)
        else:
            break
    #increment your counter
    c+=1
    #increase i to the index of the file name that is not equal to the one that
    #you started with
    i=j

根据您的需要修改此代码很容易。

于 2013-10-28T02:21:05.370 回答
0

我会做这样的事情。

filenames =['file_IL.txt', 'file_IL.csv',
            'file_NY.txt', 'file_NY.csv']
extensions = {b:[] for b in set([x.split('.')[0] for x in filenames])}
newnames = []

for fname in filenames:
    extensions[fname.split('.')[0]].append(fname)

for i,fnames in enumerate(extensions.values()):
    for fname in fnames:
        newnames.append('{0}_{1:03d}'.format(fname, i))
于 2013-10-28T02:26:02.037 回答