0

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.

2
  • But, when you sort the list in memory of python objects. This is the same as sort list but you need first read the file. Commented May 13, 2015 at 12:26
  • 1
    You don't have to compare the first, second and third place individually. Just read the lines as lists/tuples and sort those. Commented May 13, 2015 at 12:27

4 Answers 4

3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

What about [2, 0, 0] \n [11, 0, 0]?
@tobias_k How about now?
0

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

1 Comment

eval isn't a great idea.
0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.