首页 > 解决方案 > 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()

标签: pythonfileencodingcjk

解决方案


删除编码参数,因为您以编码模式打开文件,因此您无法加入字符串上的任何子字符串。 所以你的代码将是——

# ...
    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()

推荐阅读