Pro*_*r12 -1 python text-files
这是我的代码:
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')
Run Code Online (Sandbox Code Playgroud)
我收到错误:
hisEasyRFile.write(score, '|' , username , '\n')
TypeError: function takes exactly 1 argument (4 given)
Run Code Online (Sandbox Code Playgroud)
知道为什么会这样吗?此外,'得分'是一个整数.这可能会影响它吗?我不相信它可以写整数到文件虽然是吗?我需要它是一个整数以供将来使用,但如果我需要将它转换为字符串,有没有办法在我读取文件后将其转换回整数?
你似乎对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))
Run Code Online (Sandbox Code Playgroud)
要么
# assuming you expected there to be spaces between the arguments, as print() would do
# Add sep='' if you don't want them added. print() adds a newline
print(score, '|', username, file=hisEasyRFile)
Run Code Online (Sandbox Code Playgroud)
该file=...参数print()告诉它输出重定向到文件对象.
如果你想编写以字符分隔的值(逗号,制表符,或者在本例中为|条形字符),你应该真正使用该csv模块:
import csv
with open("hisEasyR.txt", "a") as hisEasyRFile:
writer = csv.writer(hisEasyRFile, delimiter='|')
writer.writerows(results)
Run Code Online (Sandbox Code Playgroud)
这将在一个步骤中写入所有列表,每个列表都|将值作为分隔符.转换为字符串将为您处理.这里没有添加空格.