Introduce
CSV (cmma-separated values) is a comma-separated value (also known as a character-delimited value, because the delimiter can be not a comma) shorthand. is a commonly used text format for storing tabular data, including numbers or characters.
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.
This article gives an example of some of the most commonly used functions in the CSV module.
For more information, see official website: https://docs.python.org/2/library/csv.html
Getting Start
The main functions of the CSV module in Python are the following two:
-
csv.reader(csvfile, dialect=‘excel‘, **fmtparams)
- Return value: A reader object that can be iterated, with a line_num parameter representing the current number of rows
- Parameter table:
- CSVFile
You need to be an object that supports iterations (Iterator), and the return value of each call to the next method is a string (string), the usual file object, or the list object is applicable
- Dialect
Encoding style, the default is Excel, that is, comma (,) separated, and the CSV module also supports Excel-tab style, that is, tab (tab) separation. Other ways need to be defined, and then you can call the Register_dialect method to register, and the List_dialects method to query the list of all coded styles that have been registered.
- Fmtparam
A format parameter that overrides the encoding style specified by the previous dialect object.
-
csv.writer(csvfile, dialect=‘excel‘, **fmtparams)
- Return value: Returns a Writer object with two functions Writerow () and Writerows ()
- Parameter table: Same as parameter table for Csv.reader ()
Example
ImportCsv# Read a CSV fileMyfilepath =' C:/users/a/desktop/mytablib.csvnew '# The Open you use here should be added newline= ' Otherwise there will be one more line break (as the standard library document says)MyFile = open (Myfilepath,' R ', newline="') myreader = Csv.reader (myfile) forRowinchmyreader:ifMyreader.line_num = =1:# Line_num is counted starting from 1. Continue forIinchRow:# Row is a listPrint (I, end="') print () Myfile.close ()# Remember the close file# Write a file that already existsMyFile = open (Myfilepath,' A ', newline="')# Open files using append modeMywriter = Csv.writer (myfile) Mywriter.writerow ((3,' Wang ', -))# Join a rowMywriter.writerow ((4,' Zhou ', -)) Mywriter.writerows ([[5,' Zhao ', -],[6,' Qian ', -]])# Add multiple linesMyfile.close ()
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Python CSV Module Learning