Pyjo.File - File system paths

from Pyjo.File import File

# Portably deal with file system paths
path = File('/home/sri/.vimrc')
print(path.slurp())
print(path.dirname())
print(path.basename())
print(path.extname)
print(path.sibling('.bashrc'))

# Or import the module, as in Google Python Style Guide

import Pyjo.File

# Portably deal with file system paths
path = Pyjo.File.new('/home/sri/.vimrc')
print(path.slurp())
print(path.dirname())
print(path.basename())
print(path.extname)
print(path.sibling('.bashrc'))

# Use the alternative constructor
from Pyjo.File import path
path = path('/tmp/foo/bar').make_path()
path.child('test.txt').spew('Hello Pyjo!')

Pyjo.File is a container for file system paths that provides a friendly API for dealing with different operating systems. It keeps the path as it is given, and it is an os.PathLike, so the standard library takes it where it takes a path.

# Use the path with the standard library
path = Pyjo.File.new('/home/sri/test')
with open(path) as f:
    print(f.read())

See also

Pyjoyment, https://mojolicious.org.

Ported from Mojo::File of Mojolicious 9.49.

Functions

class Pyjo.File.Pyjo_File(*parts: Anything)[source]

Pyjo.File inherits all methods from Pyjo.Base and Pyjo.String.Mixin and implements the following new ones.

__bool__() → bool[source]
boolean = bool(path)

Always true.

__fspath__() → str[source]
string = os.fspath(path)

The path for the standard library, as to_str() gives it.

__getitem__(index: int) → str[source]
part = path[0]

A part of the path, as to_list() gives it.

__iter__() → Iterator[str][source]
for part in path:
    ...

Iterate the parts of the path, as to_list() gives them.

__len__() → int[source]
size = len(path)

Number of the parts of the path.

basename(*suffixes: str) → str[source]
name = path.basename()
name = path.basename('.txt')

Return the last level of the path, as File::Basename of Perl does.

# ".vimrc" (on UNIX)
path('/home/sri/.vimrc').basename()

# "test" (on UNIX)
path('/home/sri/test.txt').basename('.txt')
child(*parts: Anything) → Self[source]
child = path.child('.vimrc')

Return a new Pyjo.File object relative to the path. A child of a temporary directory keeps the directory as long as it is kept.

# "/home/sri/.vimrc" (on UNIX)
path('/home').child('sri', '.vimrc')
chmod(mode: int) → Self[source]
path = path.chmod(0o644)

Change file permissions.

copy_to(to: Anything) → Self[source]
destination = path.copy_to('/home/sri')
destination = path.copy_to('/home/sri/.vimrc.backup')

Copy file with shutil and return the destination as a Pyjo.File object.

dirname() → Self[source]
name = path.dirname()

Return all but the last level of the path, as File::Basename of Perl does, as a Pyjo.File object.

# "/home/sri" (on UNIX)
path('/home/sri/.vimrc').dirname()
download(url: Anything, *, headers: dict[str, Any] | None = None, ua: Pyjo_UserAgent | None = None) → bool[source]
boolean = path.download('https://example.com/test.tar.gz')
boolean = path.download('https://example.com/test.tar.gz', headers={'Accept': '*/*'})
boolean = path.download('https://example.com/test.tar.gz', ua=Pyjo.UserAgent.new())

Download file from URL, returns true once the file has been downloaded completely. Incomplete downloads are resumed. Follows 10 redirects by default and does not limit the size of the response, which will be streamed memory efficiently. Note that this method is EXPERIMENTAL and might change without warning!

property exists: bool[source]
boolean = path.exists

Check if the path exists, as os.path.exists() does: a symbolic link is followed, so a broken one does not exist, and neither does a path that cannot be checked, as without the permission.

# Read the configuration if there is one
if (file := path('/etc/myapp.conf')).exists:
    print(file.slurp('UTF-8'))
expanduser() → Self[source]
expanded = path.expanduser()

Return a new Pyjo.File object of the path with ~ or ~user at its beginning replaced by the home directory of the user, as os.path.expanduser() does, of HOME, or of USERPROFILE on Windows, and with the path as it is without them or when the home directory is unknown.

# "/home/sri/.aws/config" (on UNIX)
path('~/.aws/config').expanduser()

# The file of an environment variable, or the default one
path(os.environ.get('AWS_CONFIG_FILE', '~/.aws/config')).expanduser()
property extname: str[source]
ext = path.extname

Return file extension of the path.

# "js"
path('/home/sri/test.js').extname
property is_abs: bool[source]
boolean = path.is_abs

Check if the path is absolute.

# True (on UNIX)
path('/home/sri/.vimrc').is_abs

# False (on UNIX)
path('.vimrc').is_abs
property is_dir: bool[source]
boolean = path.is_dir

Check if the path is a directory, as os.path.isdir() does, following a symbolic link, and false for a path that cannot be checked.

# Create the directory unless there is one
if not (dir := path('/home/sri/myapp')).is_dir:
    dir.make_path()
property is_file: bool[source]
boolean = path.is_file

Check if the path is a regular file, as os.path.isfile() does, following a symbolic link, and false for a path that cannot be checked.

# True
curfile().is_file

# False
curfile().dirname().is_file
list(*, dir: bool = False, hidden: bool = False) → Pyjo_Collection[Self][source]
collection = path.list()
collection = path.list(hidden=True)

List all files in the directory and return a Pyjo.Collection object containing the results as Pyjo.File objects. The list does not include . and ...

# List files
for file in path('/home/sri/myapp').list().each():
    print(file)

These options are currently available:

dir

Include directories.

hidden

Include hidden files.

list_tree(*, dir: bool = False, hidden: bool = False, max_depth: int | None = None) → Pyjo_Collection[Self][source]
collection = path.list_tree()
collection = path.list_tree(hidden=True)

List all files recursively in the directory and return a Pyjo.Collection object containing the results as Pyjo.File objects. The list does not include . and .., and symbolic links to directories are not followed.

# List all templates
for file in path('/home/sri/myapp/templates').list_tree().each():
    print(file)

These options are currently available:

dir

Include directories.

hidden

Include hidden files and directories.

max_depth

Maximum number of levels to descend when searching for files.

lstat() → stat_result[source]
stat = path.lstat()

Return a os.stat_result object for the symlink.

# Get symlink size
print(path('/usr/sbin/sendmail').lstat().st_size)

# Get symlink modification time
print(path('/usr/sbin/sendmail').lstat().st_mtime)
make_path(mode: int = 511) → Self[source]
path = path.make_path()
path = path.make_path(mode=0o711)

Create the directories if they don’t already exist, with os.makedirs().

move_to(to: Anything) → Self[source]
destination = path.move_to('/home/sri')
destination = path.move_to('/home/sri/.vimrc.backup')

Move file with shutil and return the destination as a Pyjo.File object.

open(mode: str = 'r', *args: Any, **kwargs: Any) → IO[Any][source]
handle = path.open('r+')
handle = path.open('rb')
handle = path.open('r', encoding='UTF-8')

Open file with open().

realpath() → Self[source]
realpath = path.realpath()

Resolve the path with os.path.realpath() and return the result as a Pyjo.File object.

remove() → Self[source]
path = path.remove()

Delete file.

remove_tree(*, keep_root: bool = False) → Self[source]
path = path.remove_tree()
path = path.remove_tree(keep_root=True)

Delete this directory and any files and subdirectories it may contain.

sibling(*parts: Anything) → Self[source]
sibling = path.sibling('.vimrc')

Return a new Pyjo.File object relative to the directory part of the path.

# "/home/sri/.vimrc" (on UNIX)
path('/home/sri/.bashrc').sibling('.vimrc')

# "/home/sri/.ssh/known_hosts" (on UNIX)
path('/home/sri/.bashrc').sibling('.ssh', 'known_hosts')
slurp() → bytes[source]
slurp(encoding: str) → str | None
data = path.slurp()
chars = path.slurp('UTF-8')

Read all data at once from the file. If an encoding is provided, an attempt will be made to decode the content, and None is returned if it fails. A byte order mark of Unicode switches UTF-8 to its encoding, UTF-16 or UTF-32, as Windows PowerShell writes UTF-16LE, and is not a part of the characters; another encoding stays.

# "♥" of a file of b'\xff\xfee&'
path.slurp('UTF-8')
spew(content: bytes | str, encoding: str | None = None) → Self[source]
path = path.spew(data)
path = path.spew(chars, 'UTF-8')

Write all data at once to the file. If an encoding is provided, an attempt to encode the content will be made prior to writing, and characters without one are encoded with UTF-8, without a byte order mark, which the encodings UTF-8-SIG and UTF-16 of codecs write, the latter in the byte order of the machine, as Windows PowerShell 5.1 reads them.

# b'\xef\xbb\xbf\xe2\x99\xa5'
path.spew('♥', 'UTF-8-SIG').slurp()

# b'\xff\xfee&'
path.spew('\ufeff♥', 'UTF-16LE').slurp()
spurt(*chunks: bytes | str) → Self[source]
path = path.spurt(*chunks)

Alias for spew() that writes multiple chunks.

stat() → stat_result[source]
stat = path.stat()

Return a os.stat_result object for the path.

# Get file size
print(path('/home/sri/.bashrc').stat().st_size)

# Get file modification time
print(path('/home/sri/.bashrc').stat().st_mtime)
to_abs() → Self[source]
absolute = path.to_abs()

Return absolute path as a Pyjo.File object, the path does not need to exist on the file system.

to_list() → list[str][source]
parts = path.to_list()

Split the path on directory separators.

# "home:sri:.vimrc" (on UNIX)
':'.join(path('/home/sri/.vimrc').to_list())
to_path() → Path[source]
p = path.to_path()

Turn the path into pathlib.Path.

to_rel(base: Anything) → Self[source]
relative = path.to_rel('/some/base/path')

Return a relative path from the original path to the destination path as a Pyjo.File object.

# "sri/.vimrc" (on UNIX)
path('/home/sri/.vimrc').to_rel('/home')
to_str() → str[source]
string = path.to_str()

Stringify the path.

touch() → Self[source]
path = path.touch()

Create file if it does not exist or change the modification and access time to the current time.

# Safely read file
print(path('.bashrc').touch().slurp())
Pyjo.File.curfile() → Pyjo_File[source]
path = curfile()

Construct a new Pyjo.File object for the absolute path to the current source file.

Pyjo.File.path(*parts: Anything) → Pyjo_File[source]
path = path()
path = path('/home/sri/.vimrc')
path = path('/home', 'sri', '.vimrc')
path = path(tempfile.TemporaryDirectory())

Construct a new Pyjo.File object, defaults to using the current working directory.

# "foo/bar/baz.txt" (on UNIX)
path('foo', 'bar', 'baz.txt')
Pyjo.File.tempdir(template: str | None = None, **kwargs: Any) → Pyjo_File[source]
path = tempdir()
path = tempdir('tempXXXXX')

Construct a new Pyjo.File object for a temporary directory, made with tempfile.mkdtemp() and its keyword arguments, which is removed with the object or at the end of a with block, as Perl’s File::Temp removes it, without the ResourceWarning that tempfile.TemporaryDirectory gives when it is not cleaned up explicitly. The X characters at the end of a template are random, and a directory with a template is made in the current working directory, as File::Temp makes it.

# Longer version, which warns when the directory is removed with the object
path = path(tempfile.TemporaryDirectory())
Pyjo.File.tempfile(**kwargs: Any) → Pyjo_File[source]
path = tempfile()
path = tempfile(dir='/tmp')

Construct a new Pyjo.File object for a temporary file, made with tempfile.mkstemp() and its keyword arguments, which is removed with the object or at the end of a with block, as Perl’s File::Temp removes it, without the ResourceWarning that tempfile.NamedTemporaryFile() gives when it is not closed explicitly.

# Longer version, which warns when the file is removed with the object
path = path(tempfile.NamedTemporaryFile(dir='/tmp'))