Source

savReaderWriter / savReaderWriter / doc_tests / test_SavWriter_mode_ab.txt

##############################################################################
## Append some records to an existing file, using mode="ab"
##############################################################################

>>> from __future__ import print_function
>>> import shutil
>>> import os
>>> from savReaderWriter import *

## Append some records to an existing file
## First make a copy to work with (append records to)
## Also retrieve varNames and varTypes as these are mandatory args
>>> savFileName = "../savReaderWriter/test_data/Employee data.sav"
>>> crap = shutil.copy(savFileName, "Employee data copy.sav")
>>> reader = None
>>> try:  # doctest: +ELLIPSIS
...     reader = SavReader(savFileName, rawMode=True)
...     NROWS_ORIGINAL = len(reader)
...     varNames, varTypes = reader.getSavFileInfo()[2:4]
... finally:
...     # Don't forget this! You won't be able to change interface mode (ioUtf8)
...     if reader is not None:
...         reader.close()
...

## Append 100 records to the file
>>> NROWS_EXTRA = 100
>>> savFileName = "Employee data copy.sav"
>>> with SavWriter(savFileName, varNames, varTypes, mode="ab") as writer:
...     line = [1.0, 'm', 11654150400.0, 15.0, 3.0, 57000.0, 27000.0, 98.0, 144.0, 0.0]
...     for i in range(NROWS_EXTRA):
...         writer.writerow(line)

## Demonstrate that the number of records has increased by 100.
>>> reader = None
>>> try: # doctest: +ELLIPSIS
...     reader = SavReader(savFileName)
...     print(len(reader) == NROWS_ORIGINAL + NROWS_EXTRA)
... finally:
...     if reader is not None:
...         reader.close()
...
True

# clean up
>>> try:
...     os.remove(os.path.abspath(savFileName))
... except:
...     pass