csv
A port of Python 3's csv module to Larky.
This is a Larky translation of PyPI package backports.csv located here:
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.
csv.Dialect()
Describe a CSV dialect.
This must be subclassed (see csv.excel). Valid attributes are:
delimiter
, quotechar
, escapechar
, doublequote
, skipinitialspace
, lineterminator
, quoting
, strict
.
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. 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.
Example:
csvfile = StringIO("""first_name,last_name,email
... John,Doe,[email protected]
... Tom,Wright,[email protected]""")
csvreader = csv.DictReader(csvfile)
list(iter(csvreader))
[
{"first_name": "John", "last_name": "Doe", "email": "[email protected]"},
{"first_name": "Tom", "last_name": "Wright", "email": "[email protected]"},
]
Parameters:
f – any object which supports the iterator protocol and returns a string each time its next() method is called — file objects and list objects are both suitable.
fieldnames – a sequence. If fieldnames is omitted, the values in the first row of file f will be used as the fieldnames.
restkey – list of remaining data, if row has more fields than fieldnames.
restval – fill in for missing values if row has fewer fields than fieldnames.
dialect – used to define a set of parameters specific to a particular CSV dialect.
Returns: object that operates like a regular reader but maps the information in each row to a dict.
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 writerow() method contains a key not found in fieldnames, the optional extrasaction parameter indicates what action to take. If it is set to ‘raise’, the default value, a ValueError is raised. If it is set to ‘ignore’, extra values in the dictionary are ignored. Any other optional or keyword arguments are passed to the underlying writer instance.
Note that unlike the DictReader class, the fieldnames parameter of the DictWriter class is not optional.
Example:
csvfile = StringIO()
fieldnames = ["first_name", "last_name", "email"]
rows = [
... {"first_name": "John", "last_name": "Doe", "email": "[email protected]"},
... {"first_name": "Mary", "last_name": "Smith-Robinson", "email": "[email protected]"},
... {"first_name": "Dave", "last_name": "Smith", "email": "[email protected]"}]
csvwriter = csv.DictWriter(csvfile, fieldnames=fieldnames)
csvwriter.writeheader()
for r in rows:
... csvwriter.writerow(r)
csvfile.getvalue()
"first_name,last_name,email\r\n"
"John,Doe,[email protected]\r\n"
"Mary,Smith-Robinson,[email protected]\r\n"
"Dave,Smith,[email protected]\r\n"
Parameters:
f – any object which supports the iterator protocol and returns a string each time its next() method is called — file objects and list objects are both suitable.
fieldnames – a sequence of keys that identify the order in which values in the dictionary passed to the writerow() method are written to file f.
extrasaction – indicates what action to take, if the dictionary passed to the writerow() method contains a key not found in fieldnames.
restval – fill in for missing values if row has fewer fields than fieldnames.
dialect – used to define a set of parameters specific to a particular CSV dialect.
Returns: writer object responsible for converting the user’s data into delimited strings on the given file-like object.
csv.excel(init=True)
Describe the usual properties of Excel-generated CSV files.
csv.excel_tab()
Describe the usual properties of Excel-generated TAB-delimited files.
csv.field_size_limit(limit=0)
Returns the current maximum field size allowed by the parser. If new_limit is given, this becomes the new limit.
Parameters:
limit – new limit.
Returns: old limit. If limit is not given, no new limit is set and the old limit is returned.
csv.reader(fileobj, dialect='excel', **fmtparams)
Return a reader object which will iterate over lines in the given fileobj. fileobj can be any object which supports the iterator protocol and returns a string each time its __next__() method is called — file objects and list objects are both suitable. If fileobj 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).
Example:
csvfile = StringIO("""first_name,last_name,email
... John,Doe,[email protected]
... Tom,Wright,[email protected]""")
csvreader = csv.reader(csvfile)
for i, row in enumerate(iter(csvreader)):
... print(i)
... print(row)
0
["first_name", "last_name", "email"]
1
["John", "Doe", "[email protected]"]
2
["Tom", "Wright", "[email protected]"]
Parameters:
fileobj – any object which supports the iterator protocol and returns a string each time its next() method is called — file objects and list objects are both suitable.
dialect – used to define a set of parameters specific to a particular CSV dialect.
fmtparams – given to override individual formatting parameters in the current dialect.
Returns: reader object which will iterate over lines in the given fileobj.
csv.unix_dialect()
Describe the usual properties of Unix-generated CSV files.
csv.writer(fileobj, dialect='excel', **fmtparams)
Return a writer object responsible for converting the user's data into delimited strings on the given file-like object. fileobj can be any object with a write() method. If fileobj 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.
Example:
csvfile = StringIO()
rows = [
... ["first_name", "last_name", "email"],
... ["John", "Doe", "[email protected]"],
... ["Mary", "Smith-Robinson", "[email protected]"],
... ["Tom", "Wright", "[email protected]"],
... ]
csvwriter = csv.writer(csvfile)
for r in rows:
... csvwriter.writerow(r)
csvfile.getvalue()
"first_name,last_name,email\r\n"
"John,Doe,[email protected]\r\n"
"Mary,Smith-Robinson,[email protected]\r\n"
"Tom,Wright,[email protected]\r\n"
Parameters:
fileobj - any object which supports the iterator protocol and returns a string each time its next() method is called — file objects and list objects are both suitable.
dialect - used to define a set of parameters specific to a particular CSV dialect.
fmtparams - given to override individual formatting parameters in the current dialect.
Returns: writer object responsible for converting the user’s data into delimited strings on the given file-like object.
Last updated