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.Fileinherits all methods fromPyjo.BaseandPyjo.String.Mixinand implements the following new ones.- __fspath__() str[source]¶
string = os.fspath(path)
The path for the standard library, as
to_str()gives it.
- __iter__() Iterator[str][source]¶
for part in path: ...
Iterate the parts of the path, as
to_list()gives them.
- basename(*suffixes: str) str[source]¶
name = path.basename() name = path.basename('.txt')
Return the last level of the path, as
File::Basenameof 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.Fileobject 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')
- copy_to(to: Anything) Self[source]¶
destination = path.copy_to('/home/sri') destination = path.copy_to('/home/sri/.vimrc.backup')
Copy file with
shutiland return the destination as aPyjo.Fileobject.
- dirname() Self[source]¶
name = path.dirname()
Return all but the last level of the path, as
File::Basenameof Perl does, as aPyjo.Fileobject.# "/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
10redirects 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.Fileobject of the path with~or~userat its beginning replaced by the home directory of the user, asos.path.expanduser()does, ofHOME, or ofUSERPROFILEon 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.Collectionobject containing the results asPyjo.Fileobjects. The list does not include.and...# List files for file in path('/home/sri/myapp').list().each(): print(file)
These options are currently available:
dirInclude directories.
hiddenInclude 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.Collectionobject containing the results asPyjo.Fileobjects. 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:
dirInclude directories.
hiddenInclude hidden files and directories.
max_depthMaximum number of levels to descend when searching for files.
- lstat() stat_result[source]¶
stat = path.lstat()
Return a
os.stat_resultobject 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
shutiland return the destination as aPyjo.Fileobject.
- 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 aPyjo.Fileobject.
- 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.Fileobject 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
Noneis returned if it fails. A byte order mark of Unicode switchesUTF-8to 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 encodingsUTF-8-SIGandUTF-16ofcodecswrite, 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_resultobject 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.Fileobject, 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())
- Pyjo.File.curfile() Pyjo_File[source]¶
path = curfile()
Construct a new
Pyjo.Fileobject 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.Fileobject, 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.Fileobject for a temporary directory, made withtempfile.mkdtemp()and its keyword arguments, which is removed with the object or at the end of awithblock, as Perl’sFile::Tempremoves it, without theResourceWarningthattempfile.TemporaryDirectorygives when it is not cleaned up explicitly. TheXcharacters at the end of a template are random, and a directory with a template is made in the current working directory, asFile::Tempmakes 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.Fileobject for a temporary file, made withtempfile.mkstemp()and its keyword arguments, which is removed with the object or at the end of awithblock, as Perl’sFile::Tempremoves it, without theResourceWarningthattempfile.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'))