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

标签 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
    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))

关于python - 如何使用 python 按字母顺序对 .txt 文件进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28757553/

相关文章:

python - PEP0484 类型提示 : Annotating argument of given class, 不是实例

python - 以 __file__ 作为输入的abspath()

python - 扁平化列表列表

Java将对象存储在固定大小的集合中

python - 构建和比较时间

python - 如何按范围对列表元素进行分组/计数

python - 什么是__pycache__?

java - 需要一些关于 java.util.list 的说明

python : module attributes missing in python script but not in interpreter

python-2.7 - 如何找到引用点之间具有经度和纬度的所有点?