prance.util.fs

This submodule contains file system utilities for Prance.

Functions

prance.util.fs.abspath(filename, relative_to=None)[source]

Return the absolute path of a file relative to a reference file.

If no reference file is given, this function works identical to canonical_filename.

Parameters
  • filename (str) – The filename to make absolute.

  • relative_to (str) – [optional] the reference file name.

Returns

The absolute path

Return type

str

prance.util.fs.canonical_filename(filename)[source]

Return the canonical version of a file name.

The canonical version is defined as the absolute path, and all file system links dereferenced.

Parameters

filename (str) – The filename to make canonical.

Returns

The canonical filename.

Return type

str

prance.util.fs.detect_encoding(filename, default_to_utf8=True, **kwargs)[source]

Detect the named file’s character encoding.

If the first parts of the file appear to be ASCII, this function returns ‘UTF-8’, as that’s a safe superset of ASCII. This can be switched off by changing the default_to_utf8 parameter.

Parameters
  • filename (str) – The name of the file to detect the encoding of.

  • default_to_utf8 (bool) – Defaults to True. Set to False to disable treating ASCII files as UTF-8.

  • read_all (bool) – Keyword argument; if True, reads the entire file for encoding detection.

Returns

The file encoding.

Return type

str

prance.util.fs.from_posix(fname)[source]

Convert a path from posix-like, to the platform format.

Parameters

fname (str) – The filename in posix-like format.

Returns

The filename in the format of the platform.

Return type

str

prance.util.fs.is_pathname_valid(pathname)[source]

Test whether a path name is valid.

Returns

True if the passed pathname is valid on the current OS, False otherwise.

Return type

bool

prance.util.fs.read_file(filename, encoding=None)[source]

Read and decode a file, taking BOMs into account.

Parameters
  • filename (str) – The name of the file to read.

  • encoding (str) – The encoding to use. If not given, detect_encoding is used to determine the encoding.

Returns

The file contents.

Return type

unicode string

prance.util.fs.to_posix(fname)[source]

Convert a path to posix-like format.

Parameters

fname (str) – The filename to convert to posix format.

Returns

The filename in posix-like format.

Return type

str

prance.util.fs.write_file(filename, contents, encoding=None)[source]

Write a file with the given encoding.

The default encoding is ‘utf-8’. It’s recommended not to change that for JSON or YAML output.

Parameters
  • filename (str) – The name of the file to read.

  • contents (str) – The file contents to write.

  • encoding (str) – The encoding to use. If not given, detect_encoding is used to determine the encoding.