Python3 f.write UnicodeEncodeError:“utf8”编解码器无法对字符进行编码不允许使用代理

2024-10-03 17:21:25 发布

您现在位置:Python中文网/ 问答频道 /正文

在web上运行Python文件(php)。 之后,使用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()

Tags: 文件pathnameinpyinfoappread
1条回答
网友
1楼 · 发布于 2024-10-03 17:21:25

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

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

相关问题 更多 >