Getting error: write() takes no keyword arguments

∥☆過路亽.° 提交于 2019-12-20 08:06:36

问题


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')


来源:https://stackoverflow.com/questions/24167724/getting-error-write-takes-no-keyword-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!