I'm writing a game in python. And after each round of the game (yes, the game has multiple rounds) I want to write the data to a CSV file.
this is my code:
with open('data.csv', 'a') as fp:
for player in self.players:
a = csv.writer(fp, delimiter=',');
data = [[player.name, player.penalty(), player.score()]];
a.writerows(data);
the output for this code (after two rounds) in the CSV file is:
player1,10,10.0
player2,5,5.0
player1,20,15.0
player2,10,7.5
The problem is that every time the script appends data to the csv file, there is a white line between the data. And the only time I want to append a white line is between the rounds. So the output should look like this:
player1,10,10.0
player2,5,5.0player1,20,15.0
player2,10,7.5
Is there a way I can accomplish this?
My new working code:
with open('take5.csv', 'ab') as fp:
for player in self.players:
a = csv.writer(fp, delimiter=',');
data = [[player.name, player.penalty(), player.score()]];
a.writerows(data);
white_row = ['\n'];
a.writerows(white_row);
Python 3:
with open('data.csv', 'a', newline='') as fp:
for player in self.players:
a = csv.writer(fp, delimiter=',');
data = [[player.name, player.penalty(), player.score()]];
a.writerows(data);
With python 3 there is change in the CSV module you can read here
Python 2.x:
Just change the open()
to binary open('data.csv', 'ab')
You can set control quoting using:
csv.writer(fp, delimiter=',',quoting=csv.QUOTE_MINIMAL)
As from docs your options are:
csv.QUOTE_ALL Instructs writer objects to quote all fields.
csv.QUOTE_MINIMAL Instructs writer objects to only quote those fields which contain special characters such as delimiter, quotechar or any of the characters in lineterminator.
csv.QUOTE_NONNUMERIC Instructs writer objects to quote all non-numeric fields.
Instructs the reader to convert all non-quoted fields to type float.
csv.QUOTE_NONE Instructs writer objects to never quote fields. When the current delimiter occurs in output data it is preceded by the current escapechar character. If escapechar is not set, the writer will raise Error if any characters that require escaping are encountered.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With