0

I have created a text file in one program, which outputted the numbers 1 to 25 in a pseudo-random order, for example like so:

[21, 19, 14, 22, 18, 23, 25, 10, 6, 9, 1, 13, 2, 7, 5, 12, 8, 20, 24, 15, 17, 4, 11, 3, 16]

Now I have another python file which is supposed to read the file I created earlier and use a sorting algorithm to sort the numbers.

The problem is that I can't seem to figure out how to read the list I created earlier into the file as a list.

Is there actually a way to do this? Or would I be better of to rewrite my output program somehow, so that I can cast the input into a list?

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
Drosoph
  • 3
  • 3
  • You can write the list elements line by line to your file and use this http://stackoverflow.com/questions/3925614/how-do-you-read-a-file-into-a-list-in-python – cgon Nov 07 '15 at 11:58
  • Yes, but it's simpler if your original program doesn't save the brackets. And as gauden shows, it's even simpler if you leave the commas out as well. – PM 2Ring Nov 07 '15 at 12:01

2 Answers2

2

If your file looks like:

21
19
14
22
18
23
...

use this:

with open('file') as f:
    mylist = [int(i.strip()) for i in f]

If it really looks like a list like [21, 19, 14, 22...], here is a simple way:

with open('file') as f:
    mylist = list(map(int, f.read().lstrip('[').rstrip(']\n').split(', ')))

And if your file not strictly conforms to specs. For example it looks like [ 21,19, 14 , 22...]. Here is another way that use regex:

import re
with open('file') as f:
    mylist = list(map(int, re.findall('\d+', f.read())))
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
  • Probably not, since the numbers look like they're all on one line, and they're separated by commas and whitespace. – PM 2Ring Nov 07 '15 at 12:03
  • @PM2Ring Well, so you mean OP really wrote a list as string into a file? However I'll never do that... – Remi Guan Nov 07 '15 at 12:04
  • 1
    Ok, that works. Assuming the OP's file strictly conforms to specs. :) – PM 2Ring Nov 07 '15 at 12:36
  • @PM2Ring I've added another way use regex. So despite OP's file **not** strictly conforms to specs, that way can also works ;) – Remi Guan Nov 07 '15 at 12:45
  • 1
    Yes I did, and I realised that was not the brightest idea. I really appreciate the help, but I decided my output was not useful at all and rewrote the file. Thanks! :) – Drosoph Nov 10 '15 at 12:22
1

If you don't want to change the output of your current script, you may use ast.literal_eval()

import ast
with open ("output.txt", "r") as f:
    array=ast.literal_eval(f.read()) 
jayant
  • 2,349
  • 1
  • 19
  • 27
  • 1
    @KevinGuan ok thanks for the feedback. I have updated my answer to use `ast.literal_eval()` – jayant Nov 07 '15 at 12:09