Python Sorting A Text File?
So I know how to import a texfile and sort numbers such as: 1 6 4 6 9 3 5 But I don't know how to sort a data that looks like: Merchant_9976 20122 Merchant_9977 91840 Merchant_997
Solution 1:
The following will sort by the integer in the right column
withopen('file.txt', 'r') as f:
data = f.readlines()
sorted_data = sorted(data, key=lambda i: int(i.split()[1]))
print(sorted_data)
Or if you simply want them sorted by the merchant number
withopen('file.txt', 'r') as f:
data = f.readlines()
sorted_data = sorted(data)
print(sorted_data)
Solution 2:
Like Ashwini said, just use sort()
method, or better still, sorted()
function like Reymond Hettinger says.
Here we rely on the default sort order, which will use simple alphanumeric order of the string, hence order by field1 first, then field 2...
So you can simply do:
my_sorted_contents = sorted(line.strip() for line inopen('MYTEXTFILE'))
my_sorted_contents
['Merchant_9976 20122', 'Merchant_9977 91840', 'Merchant_9978 92739', 'Merchant_9979 97252', 'Merchant_9980 76885', 'Merchant_9981 67835', 'Merchant_9982 42201', 'Merchant_9983 47463']
If you actually want to split lines into fields (such that you could use a more general field-based sort order), then throw in a .split()
call before you sort.
For non-default sort orders e.g. by numeric value ("Merchant_100" > "Merchant2"), pass a comparison key, as per jpmc26's comment: sorted(... key=mykeyn )
Post a Comment for "Python Sorting A Text File?"