Austin Imperial
Austin Imperial

Reputation: 119

Sort lists inside of a text file in Python

I created code that appends a list of 6 random numbers to a text file with some rules like 3 odds & 3 even, 2 odds & 3 even etc.

Is there any way to sort lists inside of a text file? For example:

If I have a text file like this:

[2, 3, 4]
[2, 4, 5]
[3, 1, 2]
[1, 3, 4]
[1, 2, 3]

and I want to arrange/sort it like this:

[1, 2, 3]
[1, 3, 4]
[2, 3, 4]
[2, 4, 5]
[3, 1, 2]

My solution so far (But I don't know how to apply it):

  1. Just append it like 1 2 3 unlike [1, 2, 3] so that I could easily use it in my code with the help of .split()

  2. Iterate over all 1st num and sort

    If 1st num is equal to another 1st num:

    Check who has a lower 2nd num and move it on top

    If 2nd num is equal:

    Check who has a lower 3rd num and move it on top

    And so on.

Upvotes: 0

Views: 1564

Answers (4)

Malik Brahimi
Malik Brahimi

Reputation: 16711

Just sort as lists. You don't have to worry about iterations.

with open('test.txt', 'r') as text:
    nums = [ast.literal_eval(i) for i in text]
    data = [str(i) + '\n' for i in sorted(nums)]

with open('test.txt', 'w') as text:
    text.writelines(data)

Upvotes: 3

z0r
z0r

Reputation: 8575

Lists in Python are comparable with ordering as you described:

>>> [1,2,3] < [1,2,4]
True
>>> [1,2,3] >= [1,3,3]
False

If you're generating your text file in Python to begin with, you could sort the list of lists before writing the file. Or you could read the file in and parse each line, and then sort it. If you don't trust the contents of the file, you could parse each line as JSON using the json module.

This is more robust than sorting using string comparisons, because string comparison will break for numbers with varying numbers of digits.

Upvotes: 0

Gabriel Ciubotaru
Gabriel Ciubotaru

Reputation: 1082

You can read the file as lines, sort them and write them back:

out = open("out","w")
for i in sorted(open("in").readlines()):
  if i[-1] != "\n":
    i+="\n"
  out.write(i)
out.close()

Upvotes: 0

BioGeek
BioGeek

Reputation: 22827

Reads the lists from a file called original.txt and writes the sorted result to a file called sorted.txt:

with open('original.txt') as f, open('sorted.txt', 'w') as g:
    unsorted_lists = map(eval, f.read().splitlines())
    sorted_lists = sorted(unsorted_lists)
    g.write('\n'.join(map(str, sorted_lists)))

Upvotes: 0

Related Questions