按字母顺序排序 .txt 文件时出现问题(删除了一行)?

Problems while sorting alphabeticaly a .txt file (one line was dropped)?

我需要按字母顺序对包含 id 和内容列的 .txt 文件进行排序,如下所示:

SSADDS__234_234dvefeSADF, 1
SSFDS2342_234_dfsk___wewrew, 2
....
DFGFG__sasd_DFSD23423_3232, 3

然后我进行以下排序:

f=open(raw_input("give me the file"))
for word in f:
    l = sorted(map(str.strip, f))
    #print "\n",l
    a = open(r'path', 'w')
    #a.writelines(l)
    a.write('\n'.join(l)+'\n')

文件包含 500 行(id 和内容)。问题是,当我 运行 上述脚本时,我得到 499 而不是 500,为什么会这样,我该如何解决?

只需消除 for 循环即可:

from string import strip

with open(raw_input("give me the file")) as f:
    lines = sorted(map(strip, f))

    with open(r'path', 'w') as a:
        a.write('\n'.join(lines))

你的问题出在for循环中。只需删除 for 循环和 运行 您的程序,无需任何其他更改。