在python中将变量写入csv文件

o2rvlv0m  于 2023-01-28  发布在  Python
关注(0)|答案(1)|浏览(141)

我想将数据写入CSV文件,但我无法让代码写入任何变量。我正在运行大量游戏,我希望将所有数据都写入CSV文件,以显示游戏编号和结果(赢/输/平局)。

def function():
  #gets game result

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

我想要的是:

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

2eafrhcq1#

使用将扩展变量内容的格式字符串:

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

虽然我会使用csv模块,因为它可以正确处理带有分隔符和/或引号的数据列:

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])

正确使用逗号将结果引起来并转义嵌入引号的输出:

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"

要读取和解析数据:

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

相关问题