1

How to read a text file into a list with Python

"Zhang Ziyi  5"
"Phteven Tuna  4"
"Drew Barrymore  3"
"Aaron Eckhart  1"

i try to make it in to a two list

name = []
scores = []

how can i do that??

Rakesh
  • 81,458
  • 17
  • 76
  • 113
Poo Po
  • 11
  • 3
  • Read answers to this https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list – Code0987 Sep 10 '19 at 11:11
  • 1
    Possible duplicate of [How to read a file line-by-line into a list?](https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list) – Code0987 Sep 10 '19 at 11:13

2 Answers2

0

Use str.split.

Ex:

name = []
scores = []
with open("filename.txt") as infile:
    for line in infile:    #Iterate each line
        *name_val, score_val = line.strip().split()   #split by space
         name.append(" ".join(name_val))      Append name
         scores.appendint(int(score_val))     Append score
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

Find the below code:

name=[]
scores=[]
with open("text.txt",'rb+') as f:
    data = f.readlines()
lines=[d.rstrip('\n') for d in data]
for line in lines:
    name.append(line.split()[0])
    scores.append(line.split()[1])
print(name,scores)
Bharat Gera
  • 800
  • 1
  • 4
  • 13