Skip to content Skip to sidebar Skip to footer

How To Store Values Of A Particular Line Of A Text File In Separate Variables In Python

I have a text file , which reads this. a,b,c,d,e,f,g,h a,b,c,i,j,k,l,m f,k Now, I want to store the first line as a list, second list in other list. But the third two valu

Solution 1:

Method readline() returns string. To get a list you have to use:

m=fin.readline().strip().split(',')
n=fin.readline().strip().split(',')
a,b=fin.readline().strip().split(',')

Solution 2:

Use with open;

with open('my.txt') as f:
    lines = f.read().splitlines()
    # lines[0] == 'a,b,c,d,e,f,g,h'
    # lines[1] == 'a,b,c,i,j,k,l,m' 
    # lines[2] == 'f,k'
    # lines[3] == '.'

    n = list(lines[0].split(','))
    m = list(lines[1].split(','))
    a, b = lines[2].split(',')

    # n == ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h    ']
    # m == ['a', 'b', 'c', 'i', 'j', 'k', 'l', 'm    ']
    # a == f
    # b == k

Then you can do what you want with each line.

Solution 3:

Your problem lies with the fact that a,b=fin.readline() would execute fin.readline() twice, giving you a = 'f,k' and b = '.' (which is the following line that is read)

To prevent this, you could assign the previous line to a variable and then split it into variables a and b.

For example:

filename = 'input.txt'    
fin = open(filename )
n=fin.readline().split()
m=fin.readline().split()
line=(fin.readline())
a,b=line.split(',')
b=b.strip()

Or a more simplified approach using with open:

with open('input.txt') as fin:
    n=fin.readline().split()
    m=fin.readline().split()
    line=(fin.readline())
    a,b=line.split(',')
    b=b.strip()

Both of these approches would yield the output:

>>> n
['a,b,c,d,e,f,g,h']

>>> m
['a,b,c,i,j,k,l,m']

>>> a
'f'>>> b
'k'

Post a Comment for "How To Store Values Of A Particular Line Of A Text File In Separate Variables In Python"