鱼C论坛

 找回密码
 立即注册
查看: 1143|回复: 2

[已解决]for each_line in f1 为什么会显示 'gbk' 报错

[复制链接]
发表于 2020-12-28 23:33:00 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
def replace_string(old, new):
    f1 = open(file_name)
    count = 0

    for each_line in f1:
        if old in each_line:
            count += 1

    print('文件%s中共有%s【%s】\n' % (file_name, count, new))
    print('你确定要把所有的【%s】替换为【%s】\n' % (new, old))
    select = input('【YES/NO】:')
    if select == 'YES':
        f2 = open(file_name, 'w')
        f2.replace(old, new, count)
        f2.close()

    f1.close()

file_name = input('请输入文件名:')
old = input('请输入需要替换的单词或字符:')
new = input('请输入新的单词或字符:')
replace_string(old, new,)
最佳答案
2020-12-28 23:44:54
本帖最后由 jackz007 于 2020-12-28 23:48 编辑

        文件编码错误,当前缺省编码 'GBK' 无法解码文件中的中文字符。这个文件中的中文字符应该是采用了 'UTF-8' 的字符编码,打开文件的语句应该加上 encoding 选项。
  1. def replace_string(old, new):
  2.     f1 = open(file_name , encoding = 'UTF-8')    # 修改这一句
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2020-12-28 23:44:54 | 显示全部楼层    本楼为最佳答案   
本帖最后由 jackz007 于 2020-12-28 23:48 编辑

        文件编码错误,当前缺省编码 'GBK' 无法解码文件中的中文字符。这个文件中的中文字符应该是采用了 'UTF-8' 的字符编码,打开文件的语句应该加上 encoding 选项。
  1. def replace_string(old, new):
  2.     f1 = open(file_name , encoding = 'UTF-8')    # 修改这一句
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-12-28 23:45:35 | 显示全部楼层
说明不是gbk,编码方式可能是utf-8,指定encoding = 'utf-8'
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-28 20:06

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表