问题描述
gd = open("gamedata.py" , "rb+")
gd.write(CharHealth = 100)
gd.close
我收到错误消息:write() 没有关键字参数,我不知道为什么.我最好的解释是代码试图将 (CharHealth = 100)
解释为关键字参数,而不是将其写入 gamedata.py.
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.
我想将 (CharHealth = 100)
(作为一行代码)与其他代码一起写入 gamedata.py
I want to write (CharHealth = 100)
(as a line of code) along with other code to gamedata.py
推荐答案
如果你想写文本,那么传入一个bytes
对象,而不是Python语法:
If you want to write text, then pass in a bytes
object, not Python syntax:
gd.write(b'CharHealth = 100')
您需要使用 b'..'
bytes
文字,因为您以二进制模式打开文件.
You need to use b'..'
bytes
literals because you opened the file in binary mode.
Python 稍后可以读取文件并用 Python 解释内容这一事实不会改变您现在正在编写字符串的事实.
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.
注意 gd.close
什么都不做;您是在引用 close
方法而不实际调用它.最好将打开的文件对象用作上下文管理器,并让 Python 为您自动关闭它:
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 源代码是 Unicode 文本,而不是字节,真的,不需要以二进制方式打开文件,也不需要读回刚刚写的内容.使用 'w'
作为模式并使用字符串:
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')
这篇关于获取错误:write() 不接受关键字参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!