合並多個csv文件-Python


批量合並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腳本功能一致。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM