Python read/write CSV file

Source: Internet
Author: User

CSV Module method

Csv.reader

Import csv with open (' temp.csv ', ' RB ') as F:reader = Csv.reader (f) for row in Reader:print row

Csv.writer

Import csv with open (' Temp.csv ', ' WB ') as F:writer = Csv.writer (f) writer.writerow ([' A ', ' B ', ' C ']) W Riter.writerow ([' d ', ' e ', ' f '])

CSV Module class

Csv. Dictreader

Import csv with open (' temp.csv ') as F:reader = csv. Dictreader (f) for row in reader print (row[' first_name '],row[' last_name ')

Csv. Dictwriter

Import Csvwith Open (' Temp.csv ', ' W ') as F:fieldnames = [' first_name ', ' last_name '] writer = csv. Dictwriter (f, Fieldnames=fieldnames) Writer.writeheader () writer.writerow ({' first_name ': ' Ryan ', ' last_name ': ' Xu ' }) Writer.writerow ({' first_name ': ' Koko ', ' last_name ': ' Xu '})

CSV Module exception

Csv. Error

Import CSV, sys filename = ' some.csv ' with open (filename, ' RB ') as F:reader = Csv.reader (f) Try: For row in Reader:print row except CSV. Error as E:sys.exit (' file%s, line%d:%s '% (filename, reader.line_num, E))


Read objects (Dictreader instances and objects returned by the reader () function) public methods

Csvreader.next () Csvreader.line_num csvreader.fieldnames

Write Objects (Dictwriter instances and objects returned by the writer () function) public methods

Csvwriter.writerow (Row) csvwriter.writerows (rows) Csvwriter.writeheader ()


This article is from the SQL Server deep dives blog, so be sure to keep this source http://ultrasql.blog.51cto.com/9591438/1704615

Python read/write CSV file

Related Article

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.