Python--csv file read/write

Source: Internet
Author: User

Recently registered Kaggle account, practice a simple KNN algorithm for handwritten digital recognition. The downloaded training and test text is stored using a CSV file, so you can pick up the CSV module here.

    • CSV file

The CSV full name (comma-separated values) is a format file, also known as a character split value. The records are split by newline characters, each record consists of fields, and the delimiters between fields are usually commas or tabs. Typically, all records have exactly the same field sequence.

When Python processes a CSV file, you can call the built-in module CSV.

    • Read operation

Reader (CSVFile, dialect= ' Excel ', **fmtparams)

Parameters:

CSVFile, must be an object that supports iterations (Iterator), which can be a file object or a list object, or a file object that requires a "B" flag parameter when opened.
dialect, coding style, the default is the style of Excel, that is, separated by commas (,), dialect mode also supports customization, by calling the Register_dialect method to register.
Fmtparam, a format parameter used to override the encoding style specified by the previous dialect object.
# Coding:utf-8 Import CSV def read_csv (): With    open ('read_csv.csv','r' as file:        = csv.reader (file)        for in  lines:             Print l
Read CSV
['ID','name']['1','a']['2','b']['3','C']['4','D']
Read Results
    • Write operations

Writer (csvfile, dialect= ' Excel ', **fmtparams)

Parameters on the same

 def   Write_ CSV (): Result  = [[5,"  e  " ],[6, " f   " ]" with open (  "  write_csv.csv   ", "  WB   "  = Csv.writer (file) mywriter.writerow S (Result) Mywriter.writerow ([ 7, " g   ])  
Write a file

Note the time: The field read by default is a character type. Write files can be selected together with multiple records, or a single record, the record is expressed in sequence.

Python--csv file read/write

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.