files¶
Functions for filesystem and path string manipulation
OS-agnostic (Windows/Unix) - we always return Windows paths with forward slashes
supports absolute and relative paths
Does not yet support any paths that:
are not strings
contain multiple single or double-dots ( . | .. )
contain single or double-dots in the beginning/middle
- class File(path)[source]
Bases:
objectclass for keeping track of a file/folder and performing actions on it
- Parameters:
path (str) –
path to the file/folder we wish to track
- property atime: float
the last time the file/folder was accessed
wraps os.path.getatime()
given in Unix time as a float
i.e. 1663948504.5217497
- property atimes: tuple
the last time the file/folder was accessed
given as a tuple[int], starting with year and ending with microseconds
i.e. (2022, 09, 23, 10, 01, 43, 544875)
- property children: tuple
tuple of full paths for everything inside the folder
if path is empty or not a folder, returns an empty tuple
i.e. (‘C:/thisfolder/file1.txt’, ‘C:/thisfolder/file2.csv’) or ( )
- copy(dest: str, overwrite: bool = False) object[source]
copies file/folder without tracking the created copy
in-place operation
- Parameters:
dest (str) –
folder to copy file/folder into
overwrite (bool) –
whether to overwrite if the destination file/folder already exists
default: False
- property ctime: float
the time the file/folder was created
wraps os.path.getctime()
given in Unix time as a float
i.e. 1663948504.5217497
- property ctimes: tuple
the time the file/folder was created
given as a tuple[int], starting with year and ending with microseconds
i.e. (2022, 09, 23, 10, 01, 43, 544875)
- delete(force: bool = False, trash: bool = False) object[source]
deletes file/folder, attempting to recursively delete empty subfolders
in-place operation
- Parameters:
force (bool) –
whether to force deletion with shutil.rmtree()
default: False
trash (bool) –
whether to try moving item to trash/recycle bin (if enabled for that drive)
uses Send2Trash
UNSAFE - deletes file if trash/recycle bin disabled
default: False
- property exists: bool
whether the file/folder exists
wraps os.path.exists()
- property isdir: bool
whether the file/folder exists and is a folder
wraps os.path.isdir()
- property isfile: bool
whether the file/folder exists and is a file
wraps os.path.isfile()
- property isroot: bool
whether the folder is a root directory
on Unix, this is always a single forward slash ( / )
on Windows, these are drive letters ( C:/ ) or network locations ( //netloc )
- move(dest: str, overwrite: bool = False) object[source]
moves file/folder, maintaining tracking at the new location
in-place operation
- Parameters:
dest (str) –
folder to move file/folder into
overwrite (bool) –
whether to overwrite if the destination file/folder already exists
default: False
- property mtime: float
the last time the file/folder was modified
wraps os.path.getmtime()
given in Unix time as a float
i.e. 1663948504.5217497
- property mtimes: tuple
the last time the file/folder was modified
given as a tuple[int], starting with year and ending with microseconds
i.e. (2022, 09, 23, 10, 01, 43, 544875)
- property name: str
the basename of the file/folder
i.e. ‘file.txt’ or ‘foldername’
- property parent: object
the parent path of the file/folder
creates a new File instance for the parent path
- property parts: tuple
the parts of the file/folder’s path
given as a tuple[str]
i.e. (‘C:/’, ‘folder’, ‘file.txt’)
- rename(name: str) object[source]
renames file/folder without moving it
in-place operation
- Parameters:
name (str) –
new basename for the file/folder
- property root: str
the root of the file/folder’s path
i.e. ‘C:/’ or ‘//netloc’ or ‘/’
- property size: int
the size of the file/folder in bytes
wraps os.path.getsize()
- property stem: str
the basename of the file/folder without the extension
i.e. ‘file’ instead of ‘file.txt’
- property suffix: str
the extension of the file, or blank if a folder
i.e. ‘.txt’
- cd(path: str = '..') str[source]
changes the current working directory, creating it if nonexistent
wraps os.chdir()
- Parameters:
path (str) –
path to folder we want to go in
default: parent (up a folder)
- Returns:
path to new current working directory
- Return type:
str
- checkwindrive(drive: str) str[source]
checks if a given string is a Windows drive letter (i.e. ‘C:’, ‘D:\’, ‘E:/’)
- Parameters:
drive (str) –
string to check
- Returns:
normalized root path ( ‘C:/’ ) if valid, else an empty string
- Return type:
str
- checkzip(path: str) bool[source]
checks if an archive file (.7z or .zip) exists and is valid
deletes file if invalid or incomplete
does nothing to files with the wrong extension
- Parameters:
path (str) –
path to the archive file
- Returns:
True –
file exists and is valid
False –
- file doesn’t exist, because either:
we deleted it
it didn’t exist before
- copy(path: str, dest: str, overwrite: bool = False) str[source]
copies file/folder and all contents, creating destination if nonexistent
- Parameters:
path (str) –
path to desired file/folder
dest (str) –
path to destination folder (where we’re copying into)
overwrite (bool) –
whether to overwrite an existing file/folder
merges folders, but overwrites files if they exist
default: False
- Returns:
path to copied file/folder
- Return type:
str
- copymove(func)[source]
wrapper for
py416.files.copy()andpy416.files.move()copy and move are nearly the same, so this handles some of what they share
- delete(path: str, force: bool = False, trash: bool = False) None[source]
deletes file/folder
- Parameters:
path (str) –
path to file/folder
force (bool) –
whether to try shutil.rmtree() to delete a folder and its contents
default: False
trash (bool) –
whether to try moving item to trash/recycle bin (if enabled for that drive)
uses Send2Trash
UNSAFE - deletes file if trash/recycle bin disabled
default: False
- forslash(path: str) str[source]
replaces backslashes in paths with forward slashes
used to unify path formatting between OS types
- Parameters:
path (str) –
path string
- Returns:
path with forward slashes
- Return type:
str
- getcwd() str[source]
gets the current working directory
wraps os.getcwd()
- Returns:
path to current working directory
- Return type:
str
- getpath(path: str) str[source]
gets the full path of something, resolving most relative paths
- Parameters:
path (str) –
absolute or relative path
if relative, we assume it’s in the current working directory
- Returns:
absolute path
- Return type:
str
- joinpath(*parts) str[source]
joins parts of a path together in the order they were received
- Parameters:
parts (iterable) –
folder/file names to join together
iterable may be single or nested lists or tuples
- Returns:
joined path
- Return type:
str
- listdir(path: str = '.', dirs: bool = True, files: bool = True, recursive: bool = False, search: str = '', case: bool = False, recency=0, return_dict: bool = False, sort_dict: str = 'path')[source]
lists files/folders within a folder
allows for some filtering by filename and modify date
wraps os.listdir()
- Parameters:
path (str) –
folder to search in
default: current working directory
dirs (bool) –
whether to list folders
default: True
files (bool) –
whether to list files
default: True
recursive (bool) –
whether to list all files and folders recursively
if False, this will only list files/folders in the specified folder
default: False
search (str) –
like a glob, searches filenames for a specified pattern
this does not search any files, rather the list of files we already gathered
accepts Unix wildcards ( * ? […] [!…] )
default: nothing
case (bool) –
whether to exactly match capitalization of search term
does nothing if search is not set
default: False
recency (float | int | str) –
how old a file may be, so this only shows the most recently created/modified files
- type: float | int
number of seconds
- type: str
must be formatted like the base output from
py416.secmod(), i.e. “3d16h5m47s”can be missing parts, i.e. “3d47s”
capitalization is ignored
if multiple of the same type of value are passed in the string, i.e. “4h16h”, only the first value is grabbed
default: 0 (include everything)
return_dict (bool) –
whether to return a dictionary instead of a tuple
dict contains details on each file with paths as keys and dicts of their details as values
- structured like so:
{path: {‘size’: int, ‘mtime’: int, ‘mage’: str}}
- size: int
bytes
- mtime: int
modify time
Unix timestamp
- mage: str
how long ago the modify time was
return is from
py416.secmod(), i.e. ‘46d19h08m07s’
default: False
sort_dict (str) –
what to sort a returned dictionary by
accepted values: path, size, mtime, mage
always sorts in ascending order (small -> large)
sorting by mage (modify age) is reverse to sorting by mtime (modify time)
default: path
- Returns:
- dict[str (dict[str: int, str: int, str: str]]) –
absolute path, size, modify time, modify age
- tuple[str] –
absolute paths
- log(path: str, msg: str, ts: bool = True, ts_args: tuple = (1, 0, 1, 1, 1, 0), encoding: str = 'utf-8') None[source]
logs to file with current timestamp
creates file and its parent folder if nonexistent
- Parameters:
path (str) –
path to desired log file
msg (str) –
message to log
ts (bool) –
whether to include timestamp
default: True
ts_args (iterable) –
arguments to pass to
py416.timestamp()default return example: [2022-08-19 13:24:54 -06:00]
encoding (str) –
character set
default: utf-8
- makedirs(*dirs, ignore_errors: bool = True) tuple[source]
creates directories if nonexistent
wraps os.makedirs()
- Parameters:
dirs (list | str | tuple) –
- type: str
path to folder
- type: list | tuple
nestings of lists and tuples with folder path strings as base elements
ignore_errors (bool) –
whether to catch all Exceptions from
os.makedirs()useful to create as many of the requested folders as possible
default: True
- Returns:
folders we failed to create
- Return type:
tuple
- makefile(path: str, msg: str = '', overwrite: bool = False, encoding: str = 'utf-8') str[source]
creates a new file
wraps open()
- Parameters:
path (str) –
path to desired new file
msg (str) –
text to put in the file
default: nothing
overwrite (bool) –
whether to overwrite a file if it already exists
default: False
encoding (str) –
character set
default: utf-8
- Returns:
path to new file
- Return type:
str
- move(path: str, dest: str, overwrite: bool = False) str[source]
moves file/folder and all contents, creating destination if nonexistent
- Parameters:
path (str) –
path to desired file/folder
dest (str) –
path to destination folder (where we’re moving into)
overwrite (bool) –
whether to overwrite an existing file/folder
merges folders, but overwrites files if they exist
default: False
- Returns:
path to moved file/folder
- Return type:
str
- parent(path: str = '.') str[source]
gets the folder containing something
- Parameters:
path (str) –
path to find the parent of
default: current working directory
- Returns:
parent path
- Return type:
str
- readfile(path: str, encoding: str = 'utf-8') str[source]
reads text from a file
wraps open()
- Parameters:
path (str) –
path to file
encoding (str) –
character set
default: utf-8
- Returns:
all text from the file
- Return type:
str
- rename(path: str, name: str) str[source]
renames file/folder without moving it
wraps os.rename()
- Parameters:
path (str) –
path to file/folder to be renamed
name (str) –
new basename for file/folder (not path)
- Returns:
new path to file/folder
- Return type:
str
- rmdir(path: str, delroot: bool = True) int[source]
recursively deletes empty directories
wraps os.rmdir()
- Parameters:
path (str) –
folder path to delete within
delroot (bool) –
whether to delete the folder specified as well
default: True
- Returns:
number of deleted folders
- Return type:
int
- splitpath(path: str) tuple[source]
splits a path string into its parts
- Parameters:
path (str) –
path
can be absolute or relative
- Returns:
folders/file
- Return type:
tuple[str]
- unzip(path: str, remove: bool = False) None[source]
unzips archive files of type: (.7z, .gz, .rar, .tar, .zip)
- Parameters:
path (str) –
path to archive file
remove (bool) –
whether to delete archive after unzipping
default: False
- unzipdir(path: str = '.', ignore_errors: bool = True) int[source]
unzips all archive files in a folder until it is unable to continue
recursive on archive files, but not folders
deletes all archive files as it unzips
supports archive files of type: (.7z, .gz, .rar, .tar, .zip)
- Parameters:
path (str) –
folder containing archive files
default: current working directory
ignore_errors (bool) –
whether to catch all Exceptions in unzipping
useful to unzip everything possible in the directory
default: True
- Returns:
number of unzipped archives
- Return type:
int