Sorting a text file alphabetically (Python)

前端 未结 3 1595
青春惊慌失措
青春惊慌失措 2020-12-09 11:28

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

shopping = open(\'shopping.txt\')
line=shopping.readline()
while len(line)!=0:
    print         


        
相关标签:
3条回答
  • 2020-12-09 11:42

    Use sorted function.

    with open('shopping.txt', 'r') as r:
        for line in sorted(r):
            print(line, end='')
    
    0 讨论(0)
  • 2020-12-09 11:50

    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

    0 讨论(0)
  • 2020-12-09 11:51

    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.

    0 讨论(0)
提交回复
热议问题