Files

Utilitary module to handle file operations

class NamedFileLock(name)[source]

File-based lock mechanism for general locking purposes.

This class provides a way to track state across processes using a lock file. The lock file contains the PID of the capturing process.

Usage:
with NamedFileLock(name=”my_file”) as lock:

# Execute your operations

# Lock is automatically released

Initialize the named file lock mechanism.

acquire()[source]

Acquire the lock.

Return type:

None

Raises:

RuntimeError – If a lock is already active

property is_locked: bool

Check if a lock is currently active.

This checks if the lock file exists and if the PID in it is still running.

Returns:

True if a lock is active, False otherwise

Return type:

bool

property pid: int

Return the parent pid.

release()[source]

Release the terminal lock.

Return type:

None

create_folder(path, parents=False, mode=448)[source]

Try to create a new folder under the specified directory.

Return type:

None

Notes

If the folder already exists, we will skip the directory creation and log an info message. That “check” is done by catching the py:FileExistsError and py:FileNotFoundError exceptions.

Parameters:
  • path (Path) – The path of the folder that needs to be created.

  • parents (bool) – If it should create the parents folder from the given path.

  • mode (int) – The permissions of the given folder. Defaults to 0700.

guess_mimetype(attachment)[source]

Guess the mimetype of a given attachment.

Return type:

str

Parameters:

attachment (Optional[TextIOWrapper]) – The attachment to be checked for mimetype.

Returns:

The guessed mimetype or “unknown/unknown” if not found.

Return type:

str

write_file(contents, path, mode=384)[source]

Try to write contents to a given file

Return type:

None

Notes

If the folder already exists, we will skip the file creation and log an info message. That “check” is done by catching the py:FileExistsError and py:FileNotFoundError exceptions.

Parameters:
  • contents (Union[str, bytes]) – The contents that will be written to the file. Either bytes or str are expected.

  • path (Path) – The path of the file that needs to be created.

  • mode (int) – The permissions of the given file. Defaults to 0600.