Python Write CSV method summary

Source: Internet
Author: User

One of the most common ways to use pandas packages

import pandas as pd #任意的多组列表a = [1, 2,3]b = [4, 5,6]  #字典中的key值即为csv中列名dataframe = Pd. DataFrame ({ ' a_name ': A, ' B_name ': b})  #将DataFrame存储为csv, index indicates whether the row name is displayed, Default=truedataframe.to_csv (  "Test.csv", Index=false,sep= ', ')  
   a_name  b_name0       1       41 2 52 3 6

The same pandas also provides a simple read CSV method

import pandas as pddata = pd.read_csv(‘test.csv‘)

Another method is to use a CSV package, one line to write

import csv#python2可以用file替代openwith open("test.csv","w") as csvfile:     writer = csv.writer(csvfile)    #先写入columns_name    writer.writerow(["index","a_name","b_name"]) #写入多行用writerows writer.writerows([[0,1,3],[1,2,3],[2,3,4]])
index   a_name  b_name0       1       31 2 32 3 4

Read the CSV file with reader

import csvwith open("test.csv","r") as csvfile: reader = csv.reader(csvfile) #这里不需要readlines for line in reader: print line

Python Write CSV method summary

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.