Python中如何将游戏结果变量写入CSV文件?
解决CSV写入变量的问题
问题分析
你的代码存在几个关键问题:
file.write()仅接受单个字符串参数,传入两个参数会触发语法错误- 字符串中的
i是字面量,没有替换为循环的实际数字 - 未从
function()中获取返回的游戏结果 - 手动拼接CSV内容容易出现格式异常(比如结果包含逗号时会破坏结构)
修复后的代码方案
方案1:基础文件操作实现
先让 function() 返回游戏结果,再正确格式化每行内容:
def function(): # 这里替换成你获取游戏结果的实际逻辑,下面是模拟示例 import random return random.choice(["win", "lose", "draw"]) # 使用with语句自动管理文件关闭,避免资源泄漏 with open("data.csv", "w") as file: # 可选:写入表头 file.write("game,result\n") for i in range(1, 11): # 生成1到10的游戏编号 result = function() # 格式化字符串,插入变量i和result line = f"game {i},{result}\n" file.write(line)
方案2:用Python内置csv模块(更推荐)
csv模块会自动处理特殊字符,避免CSV格式错误:
import csv import random def function(): return random.choice(["win", "lose", "draw"]) with open("data.csv", "w", newline="") as file: writer = csv.writer(file) # 写入表头(可选) writer.writerow(["game", "result"]) for i in range(1, 11): result = function() writer.writerow([f"game {i}", result])
最终CSV效果
运行后会生成符合你期望的内容:
game 1,win
game 2,lose
game 3,draw
...
game 10,win
内容的提问来源于stack exchange,提问作者MarkyMoo
相关产品推荐
相关产品推荐

