MM Origin & Beyond Development : MMpy.filetools.write_all

Syntax

MMpy.filetools.write_all(data, file_path, directory=None, overwrite=False, start_row_id=1)

Description

Write data to an existing data file.

Parameters

Name
Type
Description

data 

list[dict] or pandas.DataFrame or pandas.Series

Rows of only the columns/fields to be written to the file. If data is a list[dict], the correct format is one dict per row, with fields as dict keys.

file_name

string

The name and extension of the file to open.

directory

string (optional)

The path to the directory that contains file_name. Defaults to MMpy.Project.path()

overwrite

string (optional)

One of ‘fields’, ‘file’, or None. If ‘fields’, fields that exist in the output file will be overwritten if the same fields exist in data. If ‘file’, all existing file contents will be permanently deleted and replaced by the contents of data. Defaults to None.

start_row_id

int

The row in the data file to begin writing values to. Defaults to 1 (the first row).

Returns

Type
Description

bool

True if the write succeeds.

Notes

Writes all rows in data to the data file from the start_row_id row. If there are insufficient rows, new rows will be appended. start_row_id must be >= 1.

If the output file doesn’t exist, a new file will be created.

Fields present in data that do not exist in the output file will be added, with field types detected from the data where possible. If fields in the data already exist in the file, overwrite must be “fields” to write to those fields, or “file” to replace all contents of the file, else a ValueError is raised. If overwriting fields is not desired, consider removing those fields from the input.

Examples

data = [ {'X': 1, 'Y': 2, 'Z': 3}, {'X': 2, 'Y': 3, 'Z': 4} ]
MMpy.filetools.write_all(data, "output_file.DAT")

data[1]['Z'] = 5
MMpy.filetools.write_all(data, "output_file.DAT", overwrite="fields")

# add a column, without needing to overwrite existing data
new_data = [ {'A': 'abc'}, {'A': 'def'} ] # only the new column in new_data
MMpy.filetools.write_all(new_data, "output_file.DAT")

# append to the output_file.DAT
MMpy.filetools.write_all(data, "output_file.DAT", overwrite="fields", start_row_id=len(data)+1)

# Warning: overwrite="file" permanently deletes all contents in the file before writing.
MMpy.filetools.write_all(data, "output_file.DAT", overwrite="file")

Resource ID

IDPH_FILETOOLS_WRITE_ALL