Drosoph
Drosoph

Reputation: 3

File of lists, import as individual lists in python 2.7

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?

Upvotes: 0

Views: 113

Answers (2)

Remi Guan
Remi Guan

Reputation: 22282

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

Upvotes: 2

jayant
jayant

Reputation: 2389

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

Upvotes: 1

Related Questions