Sort a text file in alphabetical order (Python)

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() 
+6
source share
3 answers

Just to show something else, and not do it in python, you can do it from the command line on Unix systems:

 sort shopping.txt -o shopping.txt 

and your file will be sorted. Of course, if you really want to use python for this: the solution offered by many other people with a read and sort file works fine

+18
source

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

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

As an alternative:

 lines = sorted(shopping.readlines()) 

The disadvantage is that you have to read the entire file in memory. If this is not a problem, you can use this simple code.

+14
source

Use the sorted function.

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

Source: https://habr.com/ru/post/978670/


All Articles