python3导出csv非常简单,现在先给发夹看看导出csv文件的实例,后面有空再写导出到excel文件
我们来先看看代码
#!/usr/bin/python3 #coding:utf-8 import pymysql import time import csv def connectMysql(): conn = False try: conn = pymysql.Connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='sulao', charset='utf8') except: print("Connect MySQL failed !") conn = False return conn def getList(): cur = connectMysql().cursor() sql = '''SELECT * FROM zbp_post WHERE log_Status=0 ORDER BY log_ID ASC''' cur.execute(sql) dat = cur.fetchall() return dat if __name__ == "__main__": start_time = time.time() with open ('article.csv', 'w', newline='') as csvfile: cvwrite = csv.writer(csvfile) cvwrite.writerow(['id','标题','简介']) for tu in getList(): cvwrite.writerow((tu[0], tu[9], tu[12])) end_time = time.time() print("写入完成,耗时 %.3fs" % (end_time - start_time))
整个代码都贴出来了,主要是
csvfile = open('article.csv', 'w', newline='') cvwrite = csv.writer(csvfile) cvwrite.writerow(('id','标题','简介'))
这段,先打开文件获取文件句柄,其中newline是用来控制不要写入一行,能够匹配到\r\n空格等,然后使用writer获取文件写入对象,最后使用writerow来一行行的写入,在实际测试中writerow中使用列表比元祖速度要更快
我们接下来看看如何读取.csv文件
#!/usr/bin/python3 #coding:utf-8 from queue import Queue import time import csv start_time = time.time() with open('article.csv', 'r') as f: render = csv.reader(f) for row in render: print(row); end_time = time.time() print("读取完成,耗时 %.3fs" % (end_time - start_time))