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

如何使用python按字母顺序对.txt文件进行排序?,python,list,python-2.7,sorting,io,Python,List,Python 2.7,Sorting,Io,我有一个.txt文件,有很多ID,比如: SDFSD_23423432_SDFSDF SHTHWREWER_234324_werew dsdfdsf_334DSFGSDF_w .... SASFSD3452345_$534253 如何创建此文件的按字母顺序排序的版本?。这就是我所尝试的: f=open(raw_input("give me the file")) for word in f: l = sorted(map(str.strip, f)) print "\n",l

我有一个.txt文件,有很多ID,比如:

SDFSD_23423432_SDFSDF
SHTHWREWER_234324_werew
dsdfdsf_334DSFGSDF_w
....
SASFSD3452345_$534253
如何创建此文件的按字母顺序排序的版本?。这就是我所尝试的:

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'

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

>>> 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'

新排序的文件。。。我感到困惑,我正在创建新版本。感谢您的反馈@thefourtheye在哪里声明
文件
变量?还有其他方法吗?。谢谢大家!感谢您的帮助,我得到了以下异常:
第8行,在a.write(l)TypeError中:需要字符缓冲区对象
知道如何修复它吗?谢谢您的帮助。我一行就得到了新文件。。。如何为列表中的每个元素指定新行?如果有多行,则可以使用。如果要逐行写入,请在每行之后添加
\n
。我使用了writelines,但仍然相同,都在一行中:
a.writelines(str(l))
。知道怎么做吗?使用
writelines(l)
not
str(l)
>>> 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))