Home > Software engineering >  python - read from file and assign into multiple lists
python - read from file and assign into multiple lists

Time:05-28

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

CodePudding user response:

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

CodePudding user response:

stolen from jonsca btw This is the method i typically use:


with open("character.txt", 'r') as f:
    lines = f.readlines()
    names = {}
    for line in lines:
        myindexkey = '<h1>'
        mykeyword = 'imlookingforthis'
        index_char = line.startswith()
        if index_char(myindexkey) and mykeyword in line:
            myaddedkeys.append(mykeyword)
        else:
            continue 
 




  • Related