MarkyMoo
MarkyMoo

Reputation: 17

Writing variables to csv files in python

I want to write data to a CSV file but I can't get my code to write any variables. I am running a large number of games and I'd like to have it all in the CSV file to show the game number and the result (win/lose/draw).

def function():
  #gets game result

file = open("data.csv", "w")
for i in range(10):
  #function()
  file.write("game i", result)
file.close()

What I'm looking to get is:

game 1, result
game 2, result
game n, result

Upvotes: 0

Views: 164

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177481

Use a format string that will expand the variable contents:

file.write(f'game {i}, {result}')

Although I'd use the csv module since it will properly handle data columns with delimiters and/or quotes in them:

import csv
with open('data.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    for i in range(10):
        result = 'some result with , and " in it'
        writer.writerow([f'game {i}', result])

Output that properly quotes a result with commas and escapes embedded quotes:

game 0,"some result with , and "" in it"
game 1,"some result with , and "" in it"
game 2,"some result with , and "" in it"
game 3,"some result with , and "" in it"
game 4,"some result with , and "" in it"
game 5,"some result with , and "" in it"
game 6,"some result with , and "" in it"
game 7,"some result with , and "" in it"
game 8,"some result with , and "" in it"
game 9,"some result with , and "" in it"

To read and parse the data:

with open('data.csv', 'r', newline='') as file:
    reader = csv.reader(file)
    for game, result in reader:
        print(game, result)

Upvotes: 1

Related Questions