TypeError:写入文件时需要一个整数(类型为str)

时间:2019-10-20 16:33:16

标签: python string types integer

我正在做一个骰子游戏,我写赢家并得分到同一文件夹中的txt文件。

我尝试将usernameone和usernametwo转换为str:

else:
    if playeronepoints>playertwopoints:
        print("player one has won")
        file=open("winners.txt","a","\n")
        file.write(usernamefirst,playereonepoints)
        file.close()
    else:
        print("player two has won")

        file=open("winners.txt","w","\n")
        file.write(usernamesecond,playertwopoints)
        file.close()

预期会写入文件,但出现TypeError:必须为整数(类型为str)

2 个答案:

答案 0 :(得分:1)

问题在于您致电open

这是方法的签名:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

只需使用open(file, 'r')

您还应该考虑使用上下文管理器:

with open(file, 'r') as fh:
    fh.write("hi")

答案 1 :(得分:0)

我明白了,你导入操作系统了吗?是的,那么它就行不通了... 如果您使用的函数形式 OS 不包含所有内容,请仅包含您需要的包,例如您使用名称和系统,然后使用这种语法:

from os import system, name

那是因为 os 有另一个名为 open() 的函数,它与我认为的 int 类型有关,而与您要使用的 open() 无关...

希望这会有所帮助。