csv --- CSV file reading and writing — Python 3.15.2 documentation
Navigation index modules | next | previous | Python » 3.15.2 documentation » The Python standard library » File Formats » csv --- CSV file reading and writing | Theme | csv --- CSV file reading and writing ¶ Source code: Lib/csv.py The so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. CSV format was used for many years prior to attempts to describe the format in a standardized way in RFC 4180 .
The lack of a well-defined standard means that subtle differences often exist in the data produced and consumed by different applications. These differences can make it annoying to process CSV files from multiple sources. Still, while the delimiters and quoting characters vary, the overall format is similar enough that it is possible to write a single module which can efficiently manipulate such data, hiding the details of reading and writing the data from the programmer.
The csv module implements classes to read and write tabular data in CSV format. It allows programmers to say, "write this data in the format preferred by Excel," or "read data from this file which was generated by Excel," without knowing the precise details of the CSV format used by Excel. Programmers can also describe the CSV formats understood by other applications or define their own special-purpose CSV formats. The csv module's reader and writer objects read and write sequences.
Programmers can also read and write data in dictionary form using the DictReader and DictWriter classes. See also PEP 305 - CSV File API The Python Enhancement Proposal which proposed this addition to Python. Module contents ¶ The csv module defines the following functions: csv. reader ( csvfile , / , dialect = 'excel' , ** fmtparams ) ¶ Return a reader object that will process lines from the given csvfile . A csvfile must be an iterable of strings, each in the reader's defined csv format.
A csvfile is most commonly a file-like object or list. If csvfile is a file object, it should be opened with newline='' . [ 1 ] An optional dialect parameter can be given which is used to define a set of parameters specific to a particular CSV dialect. It may be an instance of a subclass of the Dialect class or one of the strings returned by the list_dialects() function. The other optional fmtparams keyword arguments can be given to override individual formatting parameters in the current dialect.
For full details about the dialect and formatting parameters, see section Dialects and formatting parameters . Each row read from the csv file is returned as a list of strings. No automatic data type conversion is performed unless the QUOTE_NONNUMERIC format option is specified (in which case unquoted fields are transformed into floats). A short usage example: >>> import csv >>> with open ( 'eggs.csv' , newline = '' ) as csvfile : ... spamreader = csv . reader ( csvfile , delimiter = ' ' , quotechar = '|' ) ... for row in spamreader : ... print ( ', ' . join ( row )) Spam, Spam, Spam, Spam, Spam, Baked Beans Spam, Lovely Spam, Wonderful Spam where eggs.csv contains: Spam Spam Spam Spam Spam |Baked Beans| Spam |Lovely Spam| |Wonderful Spam| csv. writer ( csvfile , / , dialect = 'excel' , ** fmtparams ) ¶ Return a writer object responsible for converting the user's data into delimited strings on the given file-like object. csvfile can be any object with a write() method.
If csvfile is a file object, it should be opened with newline='' [ 1 ] . An optional dialect parameter can be given which is used to define a set of parameters specific to a particular CSV dialect. It may be an instance of a subclass of the Dialect class or one of the strings returned by the list_dialects() function. The other optional fmtparams keyword arguments can be given to override individual formatting parameters in the current dialect.
For full details about dialects and formatting parameters, see the Dialects and formatting parameters section. To make it as easy as possible to interface with modules which implement the DB API, the value None is written as the empty string. While this isn't a reversible transformation, it makes it easier to dump SQL NULL data values to CSV files without preprocessing the data returned from a cursor.fetch* call. All other non-string data are stringified with str() before being written.
A short usage example: import csv with open ( 'eggs.csv' , 'w' , newline = '' ) as csvfile : spamwriter = csv . writer ( csvfile , delimiter = ' ' , quotechar = '|' , quoting = csv . QUOTE_MINIMAL ) spamwriter . writerow ([ 'Spam' ] * 5 + [ 'Baked Beans' ]) spamwriter . writerow ([ 'Spam' , 'Lovely Spam' , 'Wonderful Spam' ]) which writes eggs.csv containing: Spam Spam Spam Spam Spam |Baked Beans| Spam |Lovely Spam| |Wonderful Spam| csv. register_dialect ( name , / , dialect = 'excel' , ** fmtparams ) ¶ Associate dialect with name . name must be a string.
The dialect can be specified either by passing a sub-class of Dialect , or by fmtparams keyword arguments, or both, with keyword arguments overriding parameters of the dialect. For full details about dialects and formatting parameters, see section Dialects and formatting parameters . csv. unregister_dialect ( name ) ¶ Delete the dialect associated with name from the dialect registry. An Error is raised if name is not a registered dialect name. csv. get_dialect ( name ) ¶ Return the dialect associated with name .
An Error is raised if name is not a registered dialect name. This function returns an immutable Dialect . csv. list_dialects ( ) ¶ Return the names of all registered dialects. csv. field_size_limit ( ) ¶ csv. field_size_limit ( new_limit ) Returns the current maximum field size allowed by the parser. If new_limit is given, this becomes the new limit. The csv module defines the following classes: class csv. DictReader ( f , fieldnames = None , restkey = None , restval = None , dialect = 'excel' , * args , ** kwds ) ¶ Create an object that operates like a regular reader but maps the information in each row to a dict whose keys are given by the optional fieldnames parameter.
The fieldnames parameter is a sequence . If fieldnames is omitted, the values in the first row of file f will be used as the fieldnames and will be omitted from the results. If fieldnames is provided, they will be used and the first row will be included in the results. Regardless of how the fieldnames are determined, the dictionary preserves their original ordering. If a row has more fields than fieldnames, the remaining data is put in a list and stored with the fieldname specified by restkey (which defaults to None ).
If a non-blank row has fewer fields than fieldnames, the missing values are filled-in with the value of restval (which defaults to None ). All other optional or keyword arguments are passed to the underlying reader instance. If the argument passed to fieldnames is an iterator, it will be coerced to a list . Changed in version 3.6: Returned rows are now of type OrderedDict . Changed in version 3.8: Returned rows are now of type dict .
A short usage example: >>> import csv >>> with open ( 'names.csv' , newline = '' ) as csvfile : ... reader = csv . DictReader ( csvfile ) ... for row in reader : ... print ( row [ 'first_name' ], row [ 'last_name' ]) ... Eric Idle John Cleese >>> print ( row ) {'first_name': 'John', 'last_name': 'Cleese'} where names.csv contains: first_name,last_name Eric,Idle John,Cleese class csv. DictWriter ( f , fieldnames , restval = '' , extrasaction = 'raise' , dialect = 'excel' , * args , ** kwds ) ¶ Create an object which operates like a regular writer but maps dictionaries onto output rows.
The fieldnames parameter is a sequence of keys that identify the order in which values in the dictionary passed to the writerow() method are written to file f . The optional restval parameter specifies the value to be written if the dictionary is missing a key in fieldnames . If the dictionary passed to the wri
The rest of this page is on the live site.