21

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()
Bocui
  • 459
  • 1
  • 3
  • 12

5 Answers5

58

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

Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
28

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.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Mezgrman
  • 876
  • 6
  • 11
16

Use sorted function.

with open('shopping.txt', 'r') as r:
    for line in sorted(r):
        print(line, end='')
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • 1
    Could you please let me know whether this would take all lines in memory. How would this work. Does this read input lazily. – Akshay Hazari Mar 30 '16 at 07:26
  • 2
    @AkshayHazari: `sorted()` loads all lines in memory. To avoid loading all the lines, you could call the external `sort` command or [implement it in Python](http://stackoverflow.com/a/16954837/4279) – jfs Feb 23 '17 at 08:42
  • 1
    How might this replace the existing file? – StressedBoi69420 Dec 13 '21 at 11:13
1

Using pathlib you can use:

from pathlib import Path

file = Path("shopping.txt")
print(sorted(file.read_text().split("\n")))

Or if you want to sort the file on disk

from pathlib import Path

file = Path("shopping.txt")
file.write_text(
    "\n".join(
        sorted(
            file.read_text().split("\n")
        )
    )
)
Jarno
  • 6,243
  • 3
  • 42
  • 57
0

try this

shopping = open('shopping.txt')
lines = shopping.readlines()
lines.sort()
for line in lines:
    print(line)