Question

So I have a text file that contains some text in the following format:

Largest
19 15 10
12

I want to store the information in the text in three separate variables. Lets say I want it as follow:

a = 'Largest' # just a string
b = [19, 15, 10] # a python list containing all values from the second line in the text file
c = 12 # just a number represented by a variable

How can I use readline() to do this?

Was it helpful?

Solution

With this file:

$ cat /tmp/test.txt
Largest
19 15 10
12

You can do:

>>> with open('/tmp/test.txt') as f:
...    data=f.readlines()
... 
>>> data
['Largest\n', '19 15 10\n', '12']
>>> a,b,c=data
>>> a
'Largest\n'
>>> b
'19 15 10\n'
>>> c
'12'

You file must be three lines in this case.

Better to do:

>>> a,b,c=data[0:3]

To get your SPECIFIC data from that file:

>>> a=data[0].strip()
>>> b=map(int, data[1].strip().split())
>>> c=int(data[2])
>>> a
'Largest'
>>> b
[19, 15, 10]
>>> c
12

OTHER TIPS

Format the first line as str(), use split(' ') for the second and format the third as int()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top