简体   繁体   中英

How to Read text file each line after space in python

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

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'}

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 .

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']

Looks like @TheMyth almost got it, but doesn't clean the result of the trailing newline character \n . EDIT: Nevermind, @TheMyth was right.

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!

@TheMyth 在此处输入图像描述

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