I am having some trouble reading specific data from a csv file into a list in Python. Below is an example of my csv file:
Round 1
Player1 Score Player2 Score
P1 5 P2 3
P3 2 P4 4
Round 2
Player1 Score Player2 Score
P1 3 P4 6
Round 3...
(The cells are merged across the top for Round 1 and Round 2)
I am able to append all of the data in this csv file into a list however, I am wanting to ignore the row that contain "Round 1" and the row below it that contains "Player1", "Score" etc and just append the data. The same goes for the "Round 2" row and the row below. The desired list will look something like: [[P1, 5, P2, 3][P3, 2, P4, 4][P1, 3, P4, 6]]. Below is an example of my code:
playerScores = []
with open(scoreFile) as scores
for row in csv.reader(scores)
playerScores.append(row)
Any help with this would be greatly appreciated as I am struggling (PS I tried to use "next(scoreFile)" however, it only got rid of the header "Round 1" for me)
Cheers,
What about simple if
condition?
playerScores = []
with open(scoreFile) as scores
for row in csv.reader(scores):
if row and not row[0].startswith('Round') and not row[0].startswith('Player'):
playerScores.append(row)
To start from Round 2
either you can add a new flag later_rounds
:
playerScores = []
later_rounds = False
with open(scoreFile) as scores:
for row in csv.reader(scores):
if row and row[0].startswith('Round 2'):
later_rounds = True
if later_rounds and row and not row[0].startswith('Round') and not row[0].startswith('Player'):
playerScores.append(row)
Or you can skip the beginning in another loop:
playerScores = []
with open(scoreFile) as scores:
scoreReader = csv.reader(scores)
for row in scoreReader:
if row and row[0].startswith('Round 2'):
break
for row in scoreReader:
if row and not row[0].startswith('Round') and not row[0].startswith('Player'):
playerScores.append(row)
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.