csv
文件编码格式多种多样,批量处理时容易出现问题,今天偶然看到有人提问:如何处理PowerBI批量导入csv
文件时,文件编码不一致的问题?因为我之前处理过单个csv
文件编码检测的问题,初步认为是可以利用Python解决的,今天正好是周末,便研究了一下实现方法。目标是实现csv
文件编码格式批量获取,并且按照编码格式在当前目录下创建子目录,最后将同一种编码格式的csv
文件移动至对应的子目录下,最终效果如下图:
![8988f9eed28950b20c9f5b9242484cee.png](https://i-blog.csdnimg.cn/blog_migrate/da1337895956c427bcd593b6b5b7bcd3.png)
根据项目需求,程序将用到os
, chardet
, shutil
分别用于识别文件、检测编码和移动文件,三大模块用法如下:
批量识别文件下CSV文件
import os
path = input('请输入文件夹路径: ')
files = os.listdir(path)
csv_list = []
for f in files:
if os.path.splitext(f)[1] == '.csv':
csv_list.append(path + '\\' + f)
else:
pass
编码检测
import chardet
file_code = chardet.detect(str)['encoding']
文件移动
import shutil
shutil.move(src_path, dst_path)
程序编写
根据项目需求将程序逻辑拆解为如下几个步骤:
- 批量识别目录下
csv
文件; - 检测每个文件的编码格式,创建每个编码格式的子文件夹;
- 将每个文件移动至对应的编码格式子文件夹;
程序会多次用到循环的判断以及报错的处理,完整代码如下:
import os
import chardet
import shutil
path = input('请输入文件夹路径: ')
files = os.listdir(path)
csv_list = []
for f in files:
if os.path.splitext(f)[1] == '.csv':
csv_list.append(path + '\\' + f)
else:
pass
for i in range(len(csv_list)):
with open(csv_list[i], 'rb+') as ff:
lines = ff.readline()
file_code = chardet.detect(lines)['encoding']
dst_path = os.path.split(csv_list[i])[0] + '\\' + file_code
if not os.path.exists(dst_path):
os.mkdir(dst_path)
shutil.move(csv_list[i], dst_path +'\\'+ os.path.split(csv_list[i])[1])
公众号回复gbk
获取完整代码
更多内容,扫码关注了解