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()
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With