.txt Tabular data are as follows , Where the delimiter is ’\t’, Finally, through the newline character ’\n’ Line break
Open file , Exclude the first row that is not related to the data , The valid data starting from the second row is passed to the tail 、 Split into two-dimensional list form which is easy to operate , adopt int() or float() Convert numeric string data into numeric data
with open(filepath) as f:#filepath Customize
f.readline()# Remove the first row that is not related to the data
lines=f.readlines()# Read the remaining rows with data
for i in range(len(lines)):# Cycle pair 8 Line to operate
if lines[i].endswith('\n'):
lines[i]=lines[i][:-1] # Put the at the end of the string \n Get rid of
lines[i]=lines[i].split('\t') # With \t Division
At this time, the processed lines The data is :
[['Lucy', '88', '79'], ['Lilei', '90', '88'], ['Lily', '78', '82'], ['Sam', '80', '76'], ['Dean', '79', '68'], ['Jean', '75', '78'], ['Bill', '78', '82'], ['Jim', '86', '88'], ['brook', '76', '86']]
It becomes a set of two-dimensional lists , Since then, the data operation has been connected with txt The file is completely irrelevant
The first element of each list element is Name, The second is Score1, The third one is Score2, So if you put Score1 and Score2 Each attached with 50% The weight of , stay for The two-dimensional list is processed as follows in the loop
Score=int(lines[i][1])*0.5+int(lines[i][2])*0.5#i Is a cyclic variable
The second and third data of each list element can be weighted , The first one. Name The data is output together
print(lines[i][0]+' The total score of '+str(Score))# Output the total score
The result is :
Lucy The total score of 83.5
Lilei The total score of 89.0
Lily The total score of 80.0
Sam The total score of 78.0
Dean The total score of 73.5
Jean The total score of 76.5
Bill The total score of 80.0
Jim The total score of 87.0
brook The total score of 81.0
Simple data processing for tabular string is realized
Not a tabular one is actually simpler , And it is impossible to involve data operation , After reading, there is no .txt What happened to the file . As a string , You can operate with string functions