Python read/write CSV file

Source: Internet
Author: User

CSV interpretation

Comma-separated values (comma-separated values,csv, sometimes referred to as character-delimited values, because delimited characters can also be not commas), whose files store tabular data (numbers and text) in plain text. Plain text means that the file is a sequence of characters and does not contain data that must be interpreted like a binary number. A CSV file consists of any number of records separated by a newline character, each record consists of a field, and the delimiter between the fields is another character or string, most commonly a comma or tab. Typically, all records have exactly the same sequence of fields. are usually plain text files. It is recommended to use WordPad or Notepad (NOTE) to open, and then save a new file to open with Excel, is also one of the methods.

Read CSV file

Reader (filename), you can use the reader () method to create an object that reads data from a CSV file.

Official documentation: Csv.reader (csvfile, dialect= ' Excel ', **fmtparams)//csvfile is any object that can be iterated ( if the file object is newline= ' To open it ), dialect translates into dialects for custom parsers to parse data, **fmtparams for parser parameters

When a file is read, each line of input data is parsed and a list is returned

Create a CSV file to write the following data, Python reads:

>>> with open ('Test.csv','R', newline="'As csvfile: ... reader=Csv.reader (csvfile)>>> forIinchReader: ...Print(i) ... ['name','Tel','Address',' Age']['Zhang','15111111111','Beijing',' -']['Li','13822222222','Wuhan',' -']['Liu','15933333333','Hainan',' -']

Write a CSV file

Writer (filename), using the writer method to write data

Csv.writer (csvfile, dialect= ' Excel ', **fmtparams)//parameters are exactly the same as read

Write a code to test

ImportCsvwith Open ('Test1.csv','W', newline="') as F:writer=Csv.writer (f) writer.writerow ('name','Tel','Address',' Age')) Writer.writerow ('Zhang',15111111111,'Beijing', -)) Writer.writerow ('Li',13822222222,'Wuhan', -)) Writer.writerow ('Liu',15933333333,'Hainan', -) ) with open ('Test1.csv','R', newline="') as F:reader=Csv.reader (f) forIinchReader:Print(i)
Results:

[' Name ', ' Tel ', ' address ', ' age ']
[' Zhang ', ' 15111111111 ', ' Beijing ', ' 33 ']
[' Li ', ' 13822222222 ', ' Wuhan ', ' 28 ']
[' Liu ', ' 15933333333 ', ' Hainan ', ' 25 ']

The reason why the default quotation mark pattern is different from the result of the discovery

Use quoting to set quote mode when writing files

The default is: writer = Csv.writer (f,quoting=csv. Quote_nonnumeric)//non-numeric plus quotes

Can be changed to:

Quote_all: All fields quoted

Quote_minimal: Special Field Quotes

Quote_none: No Quotes

Dialect

For custom parsers, you do not have to pass individual parameters into the reader and the writer, which can be composed together to form a dialect object

Standard library includes two dialects: Excel and Excel-tabs, default to Excel

CSV dialect parameters:

Property Default value Meaning
Delimiter , Field delimiter
Doublequote True Controls whether the QuoteChar instance is paired
Escapechar None Indicates an escape sequence
LineTerminator \ r \ n The writer uses this end line
QuoteChar " Used to surround fields with special characters
Quoting Quote_minimal Control quote Behavior
Skipinitialspace False Whitespace before character delimiter is ignored

Convert Rows to Dictionaries

Dictreader and Dictwriter classes convert rows to dictionaries rather than rows

Official document: Class CSV. Dictreader(CSVFile, Fieldnames=none, Restkey=none, Restval=none, dialect= ' Excel ', *args, **kwds)

Parameter description:

FieldNames: Dictionary key, default to first row of data

Restkey: The remaining key is given by Restkey if the number of keys in the Read row field is extra

Restkey: If the Read row field is less than the number of keys given, the remaining value is given by restval

For example the above Test1.csv file

With open ('test1.csv','r', newline=') as F:     = csv. Dictreader (f)    for in  Reader:        print(i)
Results:

{' Address ': ' Beijing ', ' name ': ' Zhang ', ' age ': ' $ ', ' tel ': ' 15111111111 '}
{' Address ': ' Wuhan ', ' name ': ' Li ', ' age ': ' + ', ' tel ': ' 13822222222 '}
{' Address ': ' Hainan ', ' name ': ' Liu ', ' age ': ' + ', ' tel ': ' 15933333333 '}

Dictwriter similar to Dictreader, providing a list as a key

writer = csv. Dictwriter (F,list)

Official document: Class CSV. Dictwriter (CSVFile, FieldNames, restval= ", extrasaction= ' raise ', dialect= ' Excel ', *args, **kwds)

More detailed explanations for access to the Python standard library

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.