简体   繁体   中英

python - read from file and assign into multiple lists

How do I make the code so it reads the file and splits it so that it can assign which lines I specify into a certain named list. I want the first 3 lines to be assigned into a list then the next 3 and so on, so it would be:

list1 = Steve, Cat, v, 2, 3, 4, 1, 28

list2 = John, Dog, h , 6, 1, 7, 2, 45

list3 = (something)

text file below named character:

Steve
Cat
v 2 3 4 1 28
John
Dog
h 6 1 7 2 45

main code below

character_file = open("character.txt", 'r')
character_list = character_file.readlines()

for character in character_list:
    print(character)
    character_list_split = character.split()

    Steve = character_list_split[0,2]
    John = character_list_split[3,5]
    
character_file.close()

print(Steve)
print(John)

Thanks for the help I'm new to python

As mentioned in the comments, using a with block will close the file automatically once it goes out of scope.

This solution grabs your lines in blocks of 3. It then places the lists into a dictionary with the name as the key. It's not practical to put the lists into variables with the names as you have done.

with open("character.txt", 'r') as f:
    lines = f.readlines()
    names = {}
    for i in range(0, len(lines), 3):
        name = lines[i].strip()
        names[name] = [name, lines[i+1].strip()] + \
            lines[i+2].strip().split(' ')

As S3DEV has kindly mentioned in the comments, this is not very effective for large files and the file object itself can be iterated rather than reading in the entire file with readlines() . I've taken a shortcut and assumed that your file will always have 3 lines for each grouping and that your file will not end in the middle of an entry.

with open("character.txt", 'r') as f:
    names = {}
    while name := f.readline().strip():
        petname = f.readline().strip()
        information = f.readline().strip().split(' ')
        names[name] = [name, petname] + information

(note: walrus operator := requires Python 3.8 or above)

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