【python案例】将大CSV文件分割为小CSV文件
我们上次写的爬虫生成csv有十多兆,大概有3万条数据,但是我只需要用100条数据,需要用三百次不重复。
在网上在了一些csv分割软件,都分割出来的有问题,详情里面如果有逗号,则会看成一个字段。
后面用php写,linux下还好,能够分割出来,windows下一直卡死,这里推荐一个lavarel的Laravel Excel库,操作起来简直酷的不要不要的。
但是php语言始终太慢,容易出错。
最后想到了用python来分割,代码如下。
# -*- coding: utf-8 -*-
#
import os
import sys
import csv
# 初始化编码
reload(sys)
sys.setdefaultencoding('utf-8')
# 读取本地csv文件
csv_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'csv','source.csv')
csv_reader = csv.reader(open(csv_path,'rb'))
csv_reader.next()
i=j=1
for row in csv_reader:
if i%102==0:
print u"CSV文件source%s已生成成功" % j
j+=1
# 写入csv
csv_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'csv','source'+str(j)+'.csv')
csv_file = file(csv_path, 'ab+')
csv_write = csv.writer(csv_file)
# 文件不存在则写入头部
if os.path.getsize(csv_path)==0:
csv_write.writerow(['v_products_image','v_products_name_1','v_products_description_1','v_products_price','v_categories_name_1','v_categories_name_2'])
# 写入数据
csv_write.writerow([row[0],row[1],row[2],row[3],row[4],row[5]])
csv_file.close()
i+=1
# 关闭连接
这里用i和j来判断,出去第一行字段名,到102行时再重新生成一个csv文件。
if i%102==0:
print u"CSV文件source%s已生成成功" % j
j+=1
生成的速度太快了。

我们再看看文件目录:

PHP中接受变量$GLOBALS[‘HTTP_RAW_POST_DATA’] 和$_POST的区别 【python案例】将mysql数据库内容分割为小CSV文件
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
86b5c6a0691bdea1348f8ae57876784d好的网站
8c50c1a2e94c651442adb2aeee79c540咋回事啊
最大能分割多大的文件?
应该没有限制,我分割的最大是18M的csv。
数据会掉么。
没发现
朋友 交换链接吗
不换哦,博客类型不一样哦。
[…] 【python案例】将大CSV文件分割为小CSV文件 […]