按字母顺序对文本文件排序(Python)

2024-03-28 19:58:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我想按字母顺序对“shopping.txt”文件进行排序

shopping = open('shopping.txt')
line=shopping.readline()
while len(line)!=0:
    print(line, end ='')
    line=shopping.readline()
#for eachline in myFile:
#    print(eachline)
shopping.close()

Tags: 文件txtforreadlinelen排序顺序字母
3条回答

为了显示不同的内容而不是在python中执行此操作,可以在Unix系统中的命令行中执行此操作:

sort shopping.txt -o shopping.txt

你的文件已经分类了。当然,如果您真的希望使用python:许多其他人提出的读取文件和排序的解决方案可以很好地工作

一个简单的方法是使用sort()sorted()函数。

lines = shopping.readlines()
lines.sort()

或者:

lines = sorted(shopping.readlines())

但是,缺点是必须将整个文件读入内存。如果这不是问题,您可以使用这个简单的代码。

使用sorted函数。

with open('shopping.txt', 'r') as r:
    for line in sorted(r):
        print(line, end='')

相关问题 更多 >