Getting error: write() takes no keyword arguments

2019-10-17 16:53发布

问题:

gd = open("gamedata.py" , "rb+")

gd.write(CharHealth = 100)

gd.close

I'm receiving the error message: write() takes no keyword arguments, and I cannot figure out why. My best interpretation is that the code is trying to interpret (CharHealth = 100) as a keyword argument instead of writing it to gamedata.py.

I want to write (CharHealth = 100) (as a line of code) along with other code to gamedata.py

回答1:

If you want to write text, then pass in a bytes object, not Python syntax:

gd.write(b'CharHealth = 100')

You need to use b'..' bytes literals because you opened the file in binary mode.

The fact that Python can later read the file and interpret the contents an Python doesn't change the fact you are writing strings now.

Note that gd.close does nothing; you are referencing the close method without actually calling it. Better to use the open file object as a context manager instead, and have Python auto-close it for you:

with open("gamedata.py" , "rb+") as gd:
    gd.write(b'CharHealth = 100')

Python source code is Unicode text, not bytes, really, no need to open the file in binary mode, nor do you need to read back what you have just written. Use 'w' as the mode and use strings:

with open("gamedata.py" , "w") as gd:
    gd.write('CharHealth = 100')