写入文本文件需要1个参数错误(使用Python)

2024-09-12 10:33:19 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码:

results = [[username, score]]

with open("hisEasyR.txt","a") as hisEasyRFile:
    for result in results:
        score = result[0]
        username = result[1]
        hisEasyRFile.write(score, '|' , username , '\n')

我得到了一个错误:

^{pr2}$

知道为什么吗? 另外,“score”是一个整数。这可能会影响它吗?我不相信把整数写入文件是不可能的,是吗?我需要它是一个整数以备将来使用,但是如果我需要把它转换成字符串,有没有办法在我读过文件后把它转换回整数呢?在


Tags: 文件代码intxtforaswithusername
1条回答
网友
1楼 · 发布于 2024-09-12 10:33:19

您似乎混淆了file.write()print()函数。文本文件上的file.write()方法只接受单个字符串参数。不能传入多个值,而且肯定不能传入字符串以外的任何值。在

使用字符串格式从多个部分生成字符串,或使用print()函数写入文件:

# assuming you expected there to be spaces between the arguments, as print() would do
# Remove those spaces around the {} placeholders if you didn't want those
hisEasyRFile.write('{} | {} \n'.format(score, username))  

或者

^{pr2}$

print()file=...参数告诉它将输出重定向到file对象。在

如果要编写字符分隔值(逗号、制表符或在本例中是|条字符),则应该使用csv模块来代替:

import csv

with open("hisEasyR.txt", "a") as hisEasyRFile:
    writer = csv.writer(hisEasyRFile, delimiter='|')
    writer.writerows(results)

这将在一个步骤中写入所有列表,每个列表的值之间用|条字符作为分隔符。字符串的转换会为您处理。此处未添加空格。在

相关问题 更多 >