简体   繁体   中英

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 values, I want to store in some particular variables say a=f, b=k.

I have made the code, but its showing error during reading the third line. Please someone help this.

Here is my code.

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

UPDATE:

with open('input.txt') as fin:
    n=fin.readline().split()
    m=fin.readline().split()

    line=(fin.readline())

a,b=line[0],line[2]

i=0

for i in range(0,len(n)): 
    if n[i]!=a:
        i+=1
    cp=i-1

i=0
for i in range(0,len(n)): 
    if n[i]!=a:
        i+=1
    posa=i-1

i=0
for i in range(0,len(n)): 
    if m[i]!=b:
        i+=1
    posb=i-1

while(posa>cp):
    posa-=1

while(posa>cp):
    posb-=1

if(cp<0):
    print("No Common Predecessor")

elif (posa<posb):
    if(posa<0):
        posa=0
    print("Common Predecessor: %s" %n[posa])

else:
    if(posb<0):
        posb=0
    print("Common Predecessor: %s" %m[posb])

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

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.

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM