Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a text file alphabetically (Python)

Tags:

python

sorting

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()
like image 297
Bocui Avatar asked Nov 25 '14 09:11

Bocui


People also ask

How do you sort text in Python?

Summary. Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest. Use the sort(reverse=True) to reverse the default sort order.

Can we sort a file in Python?

Sort is a built-in list function in python that can sort any given object in place such as integers, float, string in ascending or descending order. Besides that, it provides a special attribute called “key” using which we can customize the sorting.

How do I sort the path of a file in Python?

You can use sorted with a lambda . For the sorting criteria, you can use os to first pull just the file name (using basename ), then you can split off just the filename less the extension (using splitext ). Lastly convert to int so you sort numerically instead of lexicographically.

How do you sort a column by file in Python?

To sort CSV by multiple columns, use the sort_values() method. Sorting by multiple columns means if one of the columns has repeated values, then the sort order depends on the 2nd column mentioned under sort_values() method.


1 Answers

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

like image 75
Salvador Dali Avatar answered Sep 27 '22 21:09

Salvador Dali