小心python中文路径乱码问题,注意编码

    xiaoxiao2022-07-06  186

    假设我们有这样的一个文件路径:E:\test\中文文件夹\a.txt

    在python中

    a=r'E:\test\中文文件夹\a.txt' print(os.path.exists(a))

    运行结果是True

    但是假设我们把路径配置在一个json配置cfg.json

    { "f_path":"E:\\test\\中文文件夹\\a.txt" }

    然后

    f=open("cfg.json",'r') txt=f.read() jd = json.loads(txt) f.close() a = jd['f_path'] print(os.path.exists(a))

    运行结果是False 因为a的值的中文变成了乱码 解决办法:

    f=open("cfg.json",'r') txt=f.read() # 转成gbk编码 txt = txt.encode('gbk') jd = json.loads(txt) f.close() a = jd['f_path'] print(os.path.exists(a))
    最新回复(0)