UTF-8 BOM之坑

事情的起因是这样的,我在pycharm新建了一个以UTF-8编码的txt配置文件,内容和格式如下:

账号:********
密码:********
投诉处理电话:********

当然,如果是程序猿自己用,肯定用.conf为后缀的文件作为配置文件了,以txt主要是方便其他人用,毕竟txt几乎可以在任何Windows电脑上打开。然后用Python写了一个简单的读取配置文件的函数。

def get_account_info():
    f = open('account.txt', encoding='utf-8')
    account = f.readline().strip()[3:]
    password = f.readline().strip()[3:]
    staff_phone = f.readline().strip()[7:]
    f.close()
    return account, password, staff_phone

经过测试是能正常读取的,但是作为配置文件,被修改是不可避免的,而Windows下打开txt的默认是记事本,然后就出问题了。被修改以后重新用程序读取,会发现读取的账号信息是“:********”,而不是所期望的“********”,可以发现多了一个冒号。

当然,罪魁祸首就是这个默认的记事本了,他打开txt以后将原本的 UTF-8 编码修改为了UTF-8 BOM,而且每次修改都会这样。至于为什么会出错,这篇文章有比较好的解释:https://blog.csdn.net/LegendaryHsl/article/details/78794121,我就不啰嗦了。

比较简单的解决办法就是安装一个Notepad++,用它修改文件编码,并把他设置为打开txt文件的默认程序。这样的话,再次用Notepad++修改文件内容的话,编码就不再会被强制变成UTF-8 BOM了。

当然,更好的办法自然是这样,增强鲁棒性:

def get_account_info():
    f = open('account.txt', encoding='utf-8')
    account = f.readline().strip()
    account = account[account.find(":") + 1:]
    password = f.readline().strip()
    password = password[password.find(":") + 1:]
    staff_phone= f.readline().strip()
    staff_phone= local_extension[local_extension.find(":") + 1:]
    f.close()
    return account, password, staff_phone

 

猜你喜欢

转载自blog.csdn.net/TomorrowAndTuture/article/details/103521769