python学习&导出csv数据

群里有小伙伴要求将自己的数据导出为csv格式。首先要说明的是,我安装的python是2.7,为什么这么说,因为在导出数据的时候不同的版本有一定的差异,好了,来看一下实现代码。不需要注意读取文件方式。

#coding:utf-8
import csv
import os
#文件路径,根据自己需要,做调整
dirPath = "C:/Users/qin/Desktop/csv/"
csvfile="test.csv"

outpath=dirPath+csvfile
#如果存在该文件,则删除之前的
if(os.path.exists(outpath)):
    os.remove(outpath)
#重新创建
f = open(outpath, "w+")
f.close()

try:

        #下面这句python2.7使用的,其他版本需要调整一下
        csvfile= open(outpath, 'wb')
        writer = csv.writer(csvfile)
        #写入标题头,如果不需要注释即可
        writer.writerow(['min', "band"])
        #以下代码注释掉
        numList=[1,3,4,55,6,7,8,89]
        for item in numList:
          min=item
          band=(item+2000)

          print min,band

          writer.writerow(
              [min, band])
        #以上代码注释掉
        csvfile.close()

        print "finished"
finally:

    print "there mybe"

我们来看一些实现效果。


更多精彩内容