0

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
1
  • .write() only takes one argument, so file.write("game i", result) would have thrown an exception. Commented Jan 24, 2023 at 18:36

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.