Bocui
Bocui

Reputation: 469

Sorting a text file alphabetically (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()

Upvotes: 22

Views: 124444

Answers (6)

EarthAndMoon
EarthAndMoon

Reputation: 53

This code reads the file, sorts the lines and writes it back to the file system, without any lib (not even standard lib except the built-in functions). The other answers don't output the results or use any libs for output (pathlib, etc.), or they only print it to the command line.

input_file = "input.txt"
output_file = "output.txt"
with open(input_file) as f:
    with open(output_file, "w") as o:
        o.write("\n".join(sorted(f.read().splitlines())))

You can also put this inside a function if you have to rename multiple files:

def sort_file(input_file, output_file):
    with open(input_file) as f:
        with open(output_file, "w") as o:
            o.write("\n".join(sorted(f.read().splitlines())))

sort_file("input.txt", "output.txt")

Upvotes: 0

floatingCatsAndDogs
floatingCatsAndDogs

Reputation: 53

try this

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

Upvotes: 0

Jarno
Jarno

Reputation: 7202

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

Upvotes: 2

Mezgrman
Mezgrman

Reputation: 886

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.

Upvotes: 29

Salvador Dali
Salvador Dali

Reputation: 222461

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

Upvotes: 60

Avinash Raj
Avinash Raj

Reputation: 174696

Use sorted function.

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

Upvotes: 17

Related Questions