python - Python3 f.write UnicodeEncodeError: 'utf-8' codec can't encode characters surroates not allowed
问题描述
通过 Web (php) 运行 Python 文件。之后,在使用 Python 将韩语字符串打印到文件时发生错误。另一方面,直接使用终端运行 Python 文件不会导致错误。你知道问题是什么吗?请帮我。
error Traceback (most recent call last): File "makeApp.py", line 171,
in modify_app_info(app_name) File "makeApp.py", line 65, in modify_app_info f.write(line+"\n") UnicodeEncodeError: 'utf-8' codec can't encode characters in position 13-30: surrogates not allowed
下面是导致问题的代码。
lines = read_file(read_file_path)
f = open(read_file_path, 'r', encoding='UTF-8')
lines = f.readlines()
f.close()
f = open(write_file_path, 'w', encoding='UTF-8')
for line in lines:
if '"name": "userInputAppName"' in line:
line = ' "name": "' + app_name + '",')
continue
f.write(line+"\n")
# f.write(line)
f.close()
解决方案
删除编码参数,因为您以编码模式打开文件,因此您无法加入字符串上的任何子字符串。 所以你的代码将是——
# ...
lines = read_file(read_file_path)
f = open(read_file_path, 'r')
lines = f.readlines()
f.close()
f = open(write_file_path, 'w')
for line in lines:
if '"name": "userInputAppName"' in line:
line = ' "name": "' + app_name + '",')
continue
f.write(line+"\n")
# f.write(line)
f.close()
推荐阅读
- testing - 如何在Testlink中为用户分配编辑权限但不删除权限
- angular - 如何使用@NgRx/effects 只向服务器发送一次请求
- android - 如何在标准 android 按钮上实现圆角(@android:style/Widget.Button.Small)
- c++ - cudaMemcpy2D 未处理的异常
- javascript - 如何将 TypeScript 中的数组排序为新数组?
- java - 如何用零刻度舍入 BigDecimal
- salesforce - 如何使用 Salesforce 翻译缓存?
- qt - 国际化 Qt 小部件中的文本
- css - 根据实际定位将 CSS 三角形附加到 MatTooltip?
- javascript - 仅在页面刷新后加载反应应用程序中的样式