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