如何使用 python 按字母顺序对 .txt 文件进行排序?

How to sort alphabetically a .txt file with python?

我有一个 .txt 文件,里面有很多像这样的 ID:

SDFSD_23423432_SDFSDF
SHTHWREWER_234324_werew
dsdfdsf_334DSFGSDF_w
....
SASFSD3452345_4253

如何创建此文件的按字母顺序排序的版本?。这是我试过的:

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/of/the/new/sorted/file.txt', 'w')
    file.write(l)

但我得到这个例外:

 line 6, in <module>
    file.write(l)
TypeError: descriptor 'write' requires a 'file' object but received a 'list'

我该如何解决这个问题,以便创建一个新的按字母顺序排序的文件,每行换行,例如像这样:

id
id
id
...
id

问题是,您引用的是内部文件对象

>>> file
<type 'file'>
>>> file.write([])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: descriptor 'write' requires a 'file' object but received a 'list'

您必须写入您在代码中创建的文件对象。

a = open(r'path/of/the/new/sorted/file.txt', 'w')
a.write(str(l))