eta.util.file

Utilities for reading from and writing to external files.

Functions

append_file

Append a string to a given file.

clear

Clear the contents of a file.

ensure_dir_exists

Ensure that a directory exists, creating it if it doesn't.

ensure_file_exists

Ensure that a file exists, creating an empty file if it doesn't.

exists

Check if a file exists.

get_path

Get the absolute file path for files within this module if in_module is given as True.

load_json

Load data from a JSON file.

read_file

Read the contents of a given file as a string.

read_lines

Read the lines of a file as a list, removing whitespace lines.

remove

Remove a file if it exists.

write_file

Write a string to a given file.

write_json

Write data to a JSON file.

get_path(fname, in_module)[source]

Get the absolute file path for files within this module if in_module is given as True.

read_file(fname, in_module=False)[source]

Read the contents of a given file as a string.

Parameters:
  • fname (str) –

  • in_module (bool, default=False) –

Return type:

str

read_lines(fname, in_module=False)[source]

Read the lines of a file as a list, removing whitespace lines.

Parameters:
  • fname (str) –

  • in_module (bool, default=False) –

Return type:

list[str]

write_file(fname, data, in_module=False)[source]

Write a string to a given file.

Parameters:
  • fname (str) –

  • data (str) –

  • in_module (bool, default=False) –

append_file(fname, data, in_module=False)[source]

Append a string to a given file.

Parameters:
  • fname (str) –

  • data (str) –

  • in_module (bool, default=False) –

load_json(fname, in_module=False)[source]

Load data from a JSON file.

Parameters:
  • fname (str) –

  • in_module (bool, default=False) –

Return type:

dict

write_json(fname, data, in_module=False, pretty=False)[source]

Write data to a JSON file.

Parameters:
  • fname (str) –

  • data (dict) –

  • in_module (bool, default=False) –

  • pretty (bool, default=False) – Whether to pretty-print the JSON by indenting new lines.

clear(fname, in_module=False)[source]

Clear the contents of a file.

Parameters:
  • fname (str) –

  • in_module (bool, default=False) –

exists(fname, in_module=False)[source]

Check if a file exists.

Parameters:
  • fname (str) –

  • in_module (bool, default=False) –

Return type:

bool

remove(fname, in_module=False)[source]

Remove a file if it exists.

Parameters:
  • fname (str) –

  • in_module (bool, default=False) –

ensure_dir_exists(dirname, in_module=False)[source]

Ensure that a directory exists, creating it if it doesn’t.

Parameters:
  • dirname (str) –

  • in_module (bool, default=False) –

ensure_file_exists(fname, in_module=False)[source]

Ensure that a file exists, creating an empty file if it doesn’t.

Parameters:
  • fname (str) –

  • in_module (bool, default=False) –