1. 程式人生 > 其它 >合併多個csv檔案

合併多個csv檔案

批量合併csv檔案。 使用Python實現,功能是合併批量的csv檔案(理論上也可以合併其他型別的),包括帶表頭的,只保留一個。

基礎的合併可以使用bat命令來實現:

參考了如何快速把多個csv表合併在一個表中——辦公黑科技(1) - 知乎 (zhihu.com)這篇文章:

@echo off

setlocal enabledelayedexpansion

copy *.csv new.csv

echo @@@@@@@@@@@@@合併成功!@@@@@@@@@@@@@'

pause

不過帶表頭的時候就會把標題也附加上去,所以自己寫了個python指令碼,可以簡單的實現合併檔案,包括帶表頭的情況下。

import glob

PATH = r'D:\Projects\svn\CM\trunkV2\transdatacopy'

# 合併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 continue tempfile = open(item,'r') if hastitle: next(tempfile) #skip a line combination_file
= combination_file + tempfile.read() tempfile.close print('end of processing...') return combination_file newfile = open(PATH + '\mynew.csv', 'a', encoding='utf-8') newfile.write(combine(PATH + '\*.csv',True)) newfile.close print('over')

hastitle傳入true時,就可以只保留一個表頭,傳入false和上面的bat指令碼功能一致。