Home > Mobile >  How to Read text file each line after space in python
How to Read text file each line after space in python

Time:02-01

Now I got the text file like

Mary Apple
Tom Pear
Harry Banana 
..

What I expect:

x = [ry, m, rry, ...] 
c = [Apple, Pear, Banana, ...]

How do I put the fruit into the list c and put the name(only from the thrid letter) into the list x?

Here is my code but it does't work

with open("file.txt") as f:
    data = f.readlines()
    for i in data:
        x = (i.split()[0])
    for i in data:
        c = (i.split()[1])

CodePudding user response:

You can't get both ry and om and rry. Like you could get ry with m by using the slice [2:]. Your current input and output logic doesn't make sense. However, here's something you can try:

x = []
c = []
with open("file.txt") as f:
    data = f.readlines()
    for i in data:
        x.append(i.split()[0][2:]) #ry, m, rry
        c.append(i.split()[1])
print(x,c)

You could also use list comprehension but that would just cause you to return two loops. I recommend using a dictionary for this like:

with open("file.txt") as f:
    data = f.readlines()
    values = {i.split()[0]:i.split()[1]  for i in data}
print(values)
# Output: {'Mary': 'Apple', 'Tom': 'Pear', 'Harry': 'Banana'}

CodePudding user response:

Just do like this:

with open("file.txt") as f:
    data = f.readlines()

    x = []
    c = []
    for i in data:
        line = i.split()
        x.append(line[0][2:])
        c.append(line[1])

And btw its [ry, m, rry] not om from Tom.

CodePudding user response:

with open("file.txt") as f:
    lines = f.read().splitlines() 
    x = []
    c = []
    for line in lines:
        data = line.split(" ")
        name = data[0]
        fruit = data[1]

        c.append(fruit)

        if len(name) < 4:
            x.append(name[len(name) // 2:])
        else:
            x.append(name[2:])

    print(x) # ['ry', 'om', 'rry']
    print(c) # ['Apple', 'Pear', 'Banana']

CodePudding user response:

Looks like @The Myth almost got it, but doesn't clean the result of the trailing newline character \n. The following accomplishes this:

x = []
c = []

with open("file.txt") as f:
    data = f.readlines()
    for i in data:
        x.append(i.split(' ')[0][2:])
    for i in data:
        a = i.split(' ')[1]
        c.append(a.split('\n')[0])

print(x)
print(c)

Output:

['ry', 'm', 'rry']
['Apple', 'Pear', 'Banana']

Hope that helps!

  • Related