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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27123125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:27:22  来源:igfitidea点击:

Sorting a text file alphabetically (Python)

pythonsorting

提问by Bocui

I would like to sort the file 'shopping.txt' in alphabetical order

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

回答by Avinash Raj

Use sortedfunction.

使用sorted功能。

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

回答by Mezgrman

An easy way to do this is using the sort()or sorted()functions.

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

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

Alternatively:

或者:

lines = sorted(shopping.readlines())

The disadvantage is that you have to read the whole file into memory, though. If that's not a problem, you can use this simple code.

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

回答by Salvador Dali

Just to show something different instead of doing this in python, you can do this from a command line in Unix systems:

只是为了显示一些不同的东西而不是在 python 中执行此操作,您可以从 Unix 系统中的命令行执行此操作:

sort shopping.txt -o shopping.txt

and your file is sorted. Of course if you really want python for this: solution proposed by a lot of other people with reading file and sorting works fine

并且您的文件已排序。当然,如果你真的想要 python:很多其他人提出的解决方案阅读文件和排序工作正常