当前位置:   article > 正文

python——问题解决:读取excel文件字符串,写入txt时乱码_python 读取excel文件写入txt乱码

python 读取excel文件写入txt乱码

问题

纯英文excel,excel本身并未乱码,使用xlrd库读出后字符串依然正常,在写入txt后出现乱码:
在这里插入图片描述

使用代码

def make_txt(file, data_list):
    os.remove(file)
    with open(file,"a", encoding='utf-8') as f:
        for i in range(len(data_list)):
            # print(data_list[i][1])
            try:
                if data_list[i][0] != " ":
                    f.write(str(data_list[i][0]) + " " + str(data_list[i][1]) + "\n")  
            except UnicodeEncodeError:
                pass
    print("make txt sucessfully!")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
'
运行

解决方法

在写入txt的时候,指定utf-8编码格式:

with open(file,"a", encoding='utf-8') as f:
  • 1

问题解决!

txt乱码情况解决。
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/837699
推荐阅读
相关标签
  

闽ICP备14008679号