简体   繁体   中英

TypeError: an integer is required (got type str) for writing to file

I'm making a dice game where I write the winner and score to a txt file in the same folder.

I've tried converting usernameone and usernametwo to 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()

expected to write to file but got TypeError: an integer is required (got type str)

the issue is your call to open :

here is the signature of the method:

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

Just use open(file, 'r') .

You should also consider using the context manager:

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

I figured it out, Did you import OS? is yes then it wont work... if you are using functions form OS do not include everything, include only packages you need like for example you're using name and system then use this kind of syntax:

from os import system, name

that's because os has another function called open() which has something to do with int types I presume, and has nothing to do with the open() you want to use...

hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM