Part 1: path searching
- all folders/files (including sub-folders/files) within a directory
pathlib.Path(target_dir).glob("**/*")
if only folders/sub-folders
pathlib.Path(target_dir).glob('**')
- all files/folders in current directory
pathlib.Path(target_dir).glob('*')
- all files/folders in the second current directory
pathlib.Path(target_dir).glob('*/*')
- search for a certain type of files
(1) global search including sub-directories
my_list = pathlib.Path(my_dir).rglob("*.png")
(2) only search in current directory
my_list = pathlib.Path(my_dir).glob("*.png")
Part 2: file manipulation
- delete files
from pathlib import Path
my_path = Path.cwd() / 'python' / 'libpath' / "a.txt"
assert my_path.exists(), print(my_path)
my_path.unlink()
- change file name
.with_suffix
: change the suffix name
Part 3: path relation
- add a list of sub-directories
pathlib.Path(my_path).joinpath(*argv)
- change file format name
pathlib.Path(my_file).with_suffix(".txt")
- relative path
cur_file_dir = os.path.dirname(__file__)
hydra_setting_path = os.path.relpath(hydra_setting_path, cur_file_dir)
Part 4: path elements
stem
vsname
vssuffix
stem
will not include .
when it is the last part of the path name, and this is valid regardless whether the path points to a folder or a file test1
name
will give the name with the suffix if it exists. test1.txt
suffix
will give the suffix .txt
Part 5: path info
- current working directory
Path.cwd()
is_dir
is directory?is_file
is file?
Part 6: read/write file
from pathlib import Path
my_str="hello the world"
Path("example-file.txt").write_text(my_str)str = Path("example-file.txt").read_text()
print(str)
Namely: read_bytes
, write_text
, and write_bytes
. With these four methods, you can cover the majority of your file reading/writing needs without repeatedly writing with open(...)
context managers.