Python Merge (splice) multiple CSV files __python

Source: Internet
Author: User

The author recently do data analysis and mining, often encountered to merge the problem of CSV file, just practice python then use Python Pandas library for Stitching, write down and share, we have a better way to welcome comments and exchanges.

"'
data:2017-07-13
auther; Jxnu Kerwin
Description: Use Pandas to stitch multiple CSV files to a file (that is, merge)
'
import pandas as PD
import os
folder_ Path = R ' C:\foldername '          #要拼接的文件夹及其完整路径, be careful not to include Chinese
savefile_path =  R ' C:\foldername '       #拼接后要保存的文件路径
savefile_name = R ' all.csv '              #合并后要保存的文件名

#修改当前工作目录
os.chdir (folder_path)
# Save all file names under this folder in a list
file_list = Os.listdir ()

#读取第一个CSV文件并包含表头
df = pd.read_csv (folder_path + ' \ \ + ' + file _list[0]   #编码默认UTF-8, if garbled change

#将读取的第一个CSV文件写入合并后的文件保存
df.to_csv (savefile_path+ ' \ ' + savefile_name , encoding= "Utf_8_sig", Index=false)

#循环遍历列表中各个CSV文件名, and append to the merged file for
I in range (1,len (file_list)):
    DF = pd.read_csv (Folder_path + ' \ + file_list[i])
    df.to_csv (savefile_path+ ' \ \ ' + savefile_name,encoding= ') utf_8_ Sig ", Index=false, Header=false, mode= ' + ')


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.