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

时间:2018-01-20 19:38:16

标签: 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')

我收到错误:

hisEasyRFile.write(score, '|' , username , '\n')
TypeError: function takes exactly 1 argument (4 given)

知道为什么会这样吗? 此外,'得分'是一个整数。这可能会影响它吗?我不相信它有可能将整数写入文件,不过它是吗?我需要它是一个整数以供将来使用,但如果我需要将它转换为字符串,有没有办法在我读取文件后将其转换回整数?

1 个答案:

答案 0 :(得分:6)

您似乎将<!-- :: Batch section @echo off Title Pass variable from HTA to batch for /F "delims=" %%a in ('mshta.exe "%~F0"') do set "HTAreply=%%a" echo End of HTA window, reply from HTA GUI : "%HTAreply%" Set "dest=%HTAreply%" echo robocopy "D:\MasterFolder\- Details" "E:\Sets\%dest%" /E /V /NP /R:10 /W:30 echo robocopy "D:\MasterFolder\- Details" "F:\%dest%" /E /V /NP /R:10 /W:30 pause>nul goto :EOF --> <HTML> <HEAD> <HTA:APPLICATION SCROLL="no" SYSMENU="no" > <TITLE>HTA GUI Form</TITLE> <SCRIPT language="Vbscript"> Sub window_onload() CenterWindow 200,150 Focus End Sub Sub CenterWindow(x,y) window.resizeTo x, y iLeft = window.screen.availWidth/2 - x/2 itop = window.screen.availHeight/2 - y/2 window.moveTo ileft, itop End Sub Function closeHTA(reply) Set fso = CreateObject("Scripting.FileSystemObject") fso.GetStandardStream(1).WriteLine(reply) window.close() End Function Sub Focus() txt.Focus End Sub </SCRIPT> </HEAD> <BODY> <center> <label for="dest">Please enter destination</label> <br> <input type="text" id="txt"> <br><Input type="Submit" onclick="closeHTA(txt.value)" value="Submit"> </center> </BODY> </HTML> 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))  

# 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) 的{​​{1}}参数告诉它将输出重定向到文件对象。

如果你想编写字符分隔值(逗号,制表符,或者在本例中为file=...栏字符),你应该真正使用print()模块代替:

|

这会在一个步骤中写入所有列表,每个列表的值都为csv条作为分隔符。转换为字符串将为您处理。这里没有添加空格。