新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷(xiāo)解決方案
Python拆分大型CSV文件代碼實(shí)例-創(chuàng)新互聯(lián)
這篇文章主要介紹了Python拆分大型CSV文件代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # @FileName :Test.py # @Software PyCharm import os import pandas as pd # filename為文件路徑,file_num為拆分后的文件行數(shù) # 根據(jù)是否有表頭執(zhí)行不同程序,默認(rèn)有表頭的 def Data_split(filename,file_num,header=True): if header: # 設(shè)置每個(gè)文件需要有的行數(shù),初始化為1000W chunksize=10000 data1=pd.read_table(filename,chunksize=chunksize,sep=',',encoding='gbk') # print(data1) # num表示總行數(shù) num=0 for chunk in data1: num+=len(chunk) # print(num) # chunksize表示每個(gè)文件需要分配到的行數(shù) chunksize=round(num/file_num+1) # print(chunksize) # 分離文件名與擴(kuò)展名os.path.split(filename) head,tail=os.path.split(filename) data2=pd.read_table(filename,chunksize=chunksize,sep=',',encoding='gbk') i=0 for chunk in data2: chunk.to_csv('{0}_{1}{2}'.format(head,i,tail),header=None,index=False) print('保存第{0}個(gè)數(shù)據(jù)'.format(i)) i+=1 else: # 獲得每個(gè)文件需要的行數(shù) chunksize=10000 data1=pd.read_table(filename,chunksize=chunksize,header=None,sep=',') num=0 for chunk in data1: num+=len(chunk) chunksize=round(num/file_num+1) head,tail=os.path.split(filename) data2=pd.read_table(filename,chunksize=chunksize,header=None,sep=',') i=0 for chunk in data2: chunk.to_csv('{0}_{1}{2}'.foemat(head,i,tail),header=None,index=False) print('保存第{0}個(gè)數(shù)據(jù)'.format(i)) i+=1 filename='文件路徑' #num為拆分為的文件個(gè)數(shù) Data_split(filename,num,header=True)
新聞標(biāo)題:Python拆分大型CSV文件代碼實(shí)例-創(chuàng)新互聯(lián)
本文網(wǎng)址:http://fisionsoft.com.cn/article/ieope.html