2014-12-07 22 views
0

我有許多文件標籤以字符串「example」開頭,並以一個數字(其中的順序很重要)結尾。我正在重命名所有文件(按順序),而不是按照example1,example2,example3,...,example150的順序讀取這些文件,它按照example1,example10,example100,example 101的順序讀取這些文件,例102,...,並重復這個過程。我怎樣才能改變它以順序讀取文件?謝謝!Python更改如何讀取編號的文件

+0

兩種選擇:重命名文件有領先的數字0(example000,example001等) ,或者修改你的排序以數字排序名稱而不是詞法排序。如果您想要特定的幫助,請發佈特定的代碼。 – 2014-12-07 19:41:53

回答

1

像這樣的東西?

n = .. # amount of files 
for i in range(0, n) : 
    f = open("example" + str(i), "r") 
    # do something with your file 
    f.close() 
+0

完美無缺,正是我一直在尋找的。謝謝! – Code4Days 2014-12-07 20:17:39

0
files = ['example1.txt','example2.txt', 'example10.txt','example11.txt', 'example100.txt', 'example101.txt', 'example102.txt'] 

def sort_numericly(file_list,prefix,sufix): 
    new_file_list = [] 
    for f in file_list: 
     f = f.strip(prefix).strip(sufix) 
     new_file_list.append(int(f)) 
    return [prefix+ str(f) + sufixfor f in sorted(new_file_list)] 

print sorted(files) 
print sort_numericly(files,'example','.txt') 

輸出:

['example1.txt', 'example10.txt', 'example100.txt', 'example101.txt', 'example102.txt', 'example11.txt', 'example2.txt'] 
['example1.txt', 'example2.txt', 'example10.txt', 'example11.txt', 'example100.txt', 'example101.txt', 'example102.txt'] 
1

排序採用了可用於設置分選鍵key參數。對於你的問題,你可以擺脫所有的文字,然後用int()把串入您的整數排序關鍵字:

for files in sorted(files, 
        key=lambda f: int(f.replace('example','').replace('.txt',''))): 
    # process the file 
+2

使用.strip()而不是替換;) – 2014-12-07 20:05:59

+0

f.rodrigues是對的。你可以編寫'f.strip('example.txt')'而不是替換:-)。更清潔和更一般的解決方案是使用正則表達式:'import re; ... int(re.sub(r'\ D','',f))' – 2014-12-07 20:14:38