Sorting a text file alphabetically (Python)

Deadly 提交于 2020-01-09 10:41:05

问题


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

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()

回答1:


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

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




回答2:


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

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.




回答3:


Use sorted function.

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


来源:https://stackoverflow.com/questions/27123125/sorting-a-text-file-alphabetically-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!