TypeError: write() argument must be str, not bytes
程序员文章站
2024-02-21 23:21:04
...
Python3写入二进制文件:
with open('vocab.vc','w') as f:
pickle.dump(voca,f)
wtfidf=tfidf.fit_transform(wv)
报错提示:
write输入的参数是字符串类型str,不是字节类型bytes
错误原因:
Python3中open函数添加了新参数——encoding,该参数默认值为‘utf-8’。故在文件句柄上进行read和write操作时,系统就要求开发者必须传入包含Unicode字符的实例,而不接受包含二进制数据的bytes实例。
但若是python2,就可这样写,python2.x默认编码环境是ASCII。
**注:**文件读取数据时也应用’rb’模式(二进制模式)打开文件,不使用’r’模式。
改正方法:
使用二进制写入模式(‘wb’)来开启待操作文件,不能像原来那样采用字符写入模式(‘w’)。‘wb’在python2和python3中均可用。
with open('vocab.vc','wb') as f:
pickle.dump(voca,f)
wtfidf=tfidf.fit_transform(wv)
结果:
运行成功!
下一篇: java清除u盘内存卡里的垃圾文件示例
推荐阅读
-
TypeError: write() argument must be str, not bytes
-
TypeError: write() argument must be str, not bytes
-
python write() argument must be str, not bytes
-
TypeError: write() argument must be str, not bytes
-
Python 报错TypeError: write() argument must be str, not bytes
-
TypeError: write() argument must be str, not bytes
-
[Python] TypeError: write() argument must be str, not bytes
-
TypeError: argument 1 must be 2-item sequence, not int
-
pytorch gpu版本安装外部库报错 TypeError: LoadLibrary() argument 1 must be str, not None
-
TypeError: transpose(): argument 'dim0' (position 1) must be int, not tuple