Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
按字母顺序对文本文件排序(Python)_Python_Sorting - Fatal编程技术网

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

按字母顺序对文本文件排序(Python),python,sorting,Python,Sorting,我想按字母顺序对文件“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() 使用sorted功能 with open('shop

我想按字母顺序对文件“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()

使用
sorted
功能

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

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

lines = shopping.readlines()
lines.sort()
或者:

lines = sorted(shopping.readlines())

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

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

sort shopping.txt -o shopping.txt

您的文件已排序。当然,如果你真的想用python来实现这一点:很多其他人提出的解决方案,阅读文件和排序都很好

你能告诉我这是否会占用内存中的所有行吗。这将如何工作。这是否会延迟读取输入。@AkshayHazari:
sorted()
加载内存中的所有行。为了避免加载所有行,您可以调用外部
sort
命令,或者它比从头开始编写脚本更好