[英]Lexer Outputs “TypeError: write() argument must be str, not bytes” in Python. What am I doing wrong?
I am sorry if this is only a dumb mistake, because I have little experience with Python, or programming at all. 如果这只是一个愚蠢的错误,我感到抱歉,因为我对Python或编程的经验很少。 pickle.dump(code, output)
does not like the arguments I am giving it. pickle.dump(code, output)
不喜欢我给它的参数。 How do I resolve this? 我该如何解决?
Here is the piece of sample code that outputs my file to lexer_output.txt: 这是将我的文件输出到lexer_output.txt的示例代码:
global output
output = open ("C:\\Users\Asher\Documents\BUSlang\lexer_output", "w")
pickle.dump(code, output)
The error is 错误是
"TypeError: write() argument must be str, not bytes"
The variable code
is defined earlier in the script at code=meta.read()
. 变量code
在脚本中的code=meta.read()
处已定义。 There were no other errors. 没有其他错误。
The error message is not very helpful. 该错误消息不是很有帮助。 After some trial and error I got it to work with 经过一番尝试和错误后,我开始使用它
output = open("C:\\Users\Asher\Documents\BUSlang\lexer_output", "wb")
ie the output file you want to write to must be opened in binary mode. 也就是说,您要写入的输出文件必须以二进制模式打开。
Another note: I'm not sure why you are using global output
, in your sample code it is not needed. 另一个注意事项:我不确定为什么在示例代码中不需要使用global output
。
From pickle.dump()
docs : 从pickle.dump()
docs :
The file argument must have a
write()
method that accepts a singlebytes
argument. file参数必须具有一个write()
方法,该方法接受一个bytes
参数。
"w"
file mode implies that write()
accepts str
objects, not bytes
, pass "wb"
instead. "w"
文件模式表示write()
接受str
对象(而不是bytes
,而是传递"wb"
。
You should have passed a binary file instead of the file opened in the text mode. 您应该传递一个二进制文件,而不是传递在文本模式下打开的文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.