我已經將一些文件合併在一起,但是我想要執行的操作是按照第一個字符按字母順序排列輸出。我嘗試了以下,但這不起作用。按第一個字符對文檔排序
filenames = ['1.txt', '2.txt', '3.txt']
with open('output.txt', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
for line in infile:
outfile.write(sorted(line))
這是output.txt的,因爲它代表:
NH4 ^:0.000; 1] 2 [3
H-:0.000; -1] 4 [5
CCL4:0.000; 0] 5 [3
所需output.txt:
CCL4:0.000; 0] 5 [3
H-:0.000; -1] 4 [5
NH 4:0.000; 1] 2 [3
可以告訴你,你的排序行??? – Hackaholic 2014-11-25 14:11:53
我認爲,1.txt,2.txt和3.txt的全部內容也有助於澄清事情。他們每個單行文件,還是有更多的內部? – rchang 2014-11-25 14:26:09
你真的**只是想排序每行中的第一個字符嗎? – 2014-11-25 14:29:12