批量合并csv文件。 使用Python实现,功能是合并批量的csv文件(理论上也可以合并其他类型的),包括带表头的,只保留一个。
基础的合并可以使用bat命令来实现:
参考了如何快速把多个csv表合并在一个表中——办公黑科技(1) - 知乎 (zhihu.com)这篇文章:
@echo off setlocal enabledelayedexpansion copy *.csv new.csv echo @@@@@@@@@@@@@合并成功!@@@@@@@@@@@@@' pause
不过带表头的时候就会把标题也附加上去,所以自己写了个python脚本,可以简单的实现合并文件,包括带表头的情况下。
import glob PATH = r'****************' # 合并csv文件,传入文件路径,传出合并成功的字符串 def combine(mypath,hastitle): combination_file = ''; #result csv_list =glob.glob(mypath) print('find file count:%d' % len(csv_list)) print('start combine...') index=0 #Traversal csv list for item in csv_list: if hastitle and (index == 0): tempfile = open(item,'r') combination_file = combination_file + tempfile.read() tempfile.close index += 1 continue tempfile = open(item,'r') if hastitle: next(tempfile) #skip a line combination_file = combination_file + tempfile.read() tempfile.close index += 1 print('end of processing...') return combination_file result = combine(PATH + '\*.csv',True) newfile = open(PATH + '\mynew.csv', 'a') newfile.write(result) newfile.close print('over')
hastitle传入true时,就可以只保留一个表头,传入false和上面的bat脚本功能一致。