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 path.join 在 Mac 和 Windows 中运行时的行为不同

python - 追加数字后矩阵返回 NaN

python - 如何从 Kivy 中的另一个小部件访问某些小部件属性?

python - python中小于2,000,000的素数之和

python - 使用唯一集初始化 python 列表

python - 将列表索引拆分为新列表 python

Windows 10 中的 Python PIP 路径

python - Django fixtures 和 OneToOneField

python - 未使用 Python 在 MS Fabric API 中为服务主体 token 授予身份验证

python - Python中的集合和列表有什么区别?