bag.spreadsheet.csv module

Easily import a CSV file with headers on the top row.

The most important things here are:

class bag.spreadsheet.csv.DecodingCsvWithHeaders(stream, encoding=None, **k)[source]

Bases: object

The advantage of using the class instead of the generator is that any errors related to the headers happen when the class is instantiated, so they can be catched separately.

bag.spreadsheet.csv.buffered_csv_writing(rows, encoding='utf8', headers=None, buffer_rows=50)[source]

Generate CSV lines using a buffer of size buffer_rows.

The values for the first CSV line may be provided as headers, and the remaining ones as rows, which is preferrably another generator.

For instance, in Pyramid you might have a view like this:

return Response(content_type='text/csv', app_iter=buffered_csv_writing(
    rows=my_generator, headers=['name', 'email'], buffer_rows=50))

Return the value of a Content-Disposition HTTP header.

bag.spreadsheet.csv.csv_with_headers_reader(stream, required_headers=[], forbidden_headers=[], **k)[source]

Return an iterator over a CSV reader.

It uses stream with the options passed as keyword arguments. The iterator yields objects so you can access the values conveniently.

In addition, you may pass a sequence of required_headers, and if they aren’t all present, KeyError is raised.

Let’s see an example. Suppose you are reading some CSV file and all you know is it contains the columns “Email”, “Name” and “Sex”, not necessarily in that order:

csv_reader = csv_with_headers_reader(
    open('contacts.csv', mode='r', encoding='utf8'),
    dialect="excel", delimiter=';', required_headers='email')
for o in csv_reader:
bag.spreadsheet.csv.decoding(stream, encoding='utf8')[source]

Wrap a stream that yields bytes in order to decode it.

If you have a stream that yields bytes, use this wrapper to decode them into str objects. Example:

f = open('filepath.csv', 'br')
for line in decode(f, encoding='utf8'):

This generator removes the UTF8 BOM if the file contains it.

bag.spreadsheet.csv.decoding_csv_with_headers(bytestream, encoding='utf8', **k)[source]

Combines the decoding and csv_with_headers_reader generators.

bag.spreadsheet.csv.pyramid_download_csv(response, file_title, rows, encoding='utf8', **k)[source]
bag.spreadsheet.csv.setup_reader(stream, required_headers=[], forbidden_headers=[], **k)[source]