飞道的博客

csv 文件读写乱码问题的一个简单解决方法

450人阅读  评论(0)

Python与算法社区

第 449 篇原创,干货满满

三步加星标

01

02

03

三步加星标

你好,我是 zhenguo

今天扼要总结一个处理csv文件乱码问题,可能你有类似经历,用excel打开一个csv文件,中文全部显示乱码。然后,手动用notepad++打开,修改编码为utf-8并保存后,再用excel打开显示正常。

今天使用Python,很少代码就能将上面过程自动化。首先,导入3个模块:


   
  1. # coding: utf -8
  2. # @author: zhenguo
  3. # @date:  2020 -12 -16
  4. # @describe: functions about automatic file processing
  5. import pandas as pd  
  6. import os 
  7. import chardet

chardet 模块用于得到文件的编码格式,pandas 按照这个格式读取,然后保存为xlsx格式。

获取filename文件的编码格式:


   
  1. def get_encoding(filename):
  2.      "" "
  3.     返回文件编码格式
  4.     " ""
  5.     with open(filename, 'rb') as f:
  6.          return chardet.detect(f.read())[ 'encoding']

保存为utf-8编码xlsx格式文件,支持csv, xls, xlsx 格式的文件乱码处理。需要注意,如果读入文件为csv格式,保存时要使用xlsx格式:


   
  1. def to_utf8(filename):
  2.      "" "
  3.     保存为 to_utf-8
  4.     " ""
  5.     encoding = get_encoding(filename)
  6.     ext = os.path.splitext(filename)
  7.      if ext[ 1] == '.csv':
  8.          if  'gb' in encoding or  'GB' in encoding:
  9.             df = pd.read_csv(filename,engine= 'python',encoding= 'GBK')
  10.          else:
  11.             df = pd.read_csv(filename,engine= 'python',encoding= 'utf-8')
  12.         df.to_excel(ext[ 0]+ '.xlsx')
  13.     elif ext[ 1]== '.xls' or ext[ 1] ==  '.xlsx':
  14.          if  'gb' in encoding or  'GB' in encoding:
  15.             df = pd.read_excel(filename,encoding= 'GBK')
  16.          else:
  17.             df = pd.read_excel(filename,encoding= 'utf-8')
  18.         df.to_excel(filename)
  19.      else:
  20.          print( 'only support csv, xls, xlsx format')

上面函数实现单个文件转化,下面batch_to_utf8 实现目录 path 下所有后缀为ext_name文件的批量乱码转化:


   
  1. def batch_to_utf8(path,ext_name= 'csv'):
  2.      "" "
  3.     path下,后缀为 ext_name的乱码文件,批量转化为可读文件
  4.     " ""
  5.      for file in os.listdir(path):
  6.          if os.path.splitext(file)[ 1]== '.'+ext_name:
  7.             to_utf8(os.path.join(path,file))

调用:


   
  1. if __name__ ==  '__main__':
  2.   batch_to_utf8( '.') # 对当前目录下的所有csv文件保存为xlsx格式,utf -8编码的文件

文件读写时乱码问题,经常会遇到,相信今天这篇文章里的to_utf8,batch_to_utf8函数会解决这个问题,你如果后面遇到,不妨直接引用这两个函数尝试下。

如果这个乱码解决方案有遗漏,欢迎你留言补充。最近几个月整理出来的精华资料已打包为2.0,若你有需要,微信我备注:加油包

不必打赏

给我点个赞

就心满意足了


转载:https://blog.csdn.net/xo3ylAF9kGs/article/details/111350585
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场