#common path operations
from pathlib import Path
path = Path('.')
urls = []
for f in path.iterdir():
with f.open('r', encoding='utf-8') as handle:
content = handle.read()
extracted = parser.links(content)
urls.extend(extracted)
print(urls)
with open(url_file, "a") as out_file:
out_file.write('\n'.join(urls))
\!h p = Path('..')
for f in p.glob('*.rst'): # use pathlib's glob module for pattern matching
print(f)
# even recursive glob is supported:
for f in p.glob('**/*.rst'): # or by calling rglob() instead of glob()
print(f)
root = Path('/')
subdirs = ['usr', 'local']
usr_local = root.joinpath(*subdirs)
# >>> /usr/local
# Given an existing path object, it is easy to build a
# new one with minor differences such as referring to a different file in the same directory.
ind = Path('source/pathlib/index.rst')
print(ind)
# >>> source/pathlib/index.rst
py = ind.with_name('pathlib_from_existing.py')
print(py)
# >>> source/pathlib/pathlib_from_existing.py
pyc = py.with_suffix('.pyc')
print(pyc)
# >>> source/pathlib/pathlib_from_existing.pyc
# create dir (and all parent dirs) if not existing
Path(outdir).mkdir(parents=True, exist_ok=True)
p = Path('/usr/local')
print(p.parts)
# >>> ('/', 'usr', 'local') # The sequence is a tuple, reflecting the immutability of the path instance.
p = Path('./source/pathlib/pathlib_name.py')
print(f'path : {p}')
print(f'name : {p.name}') # pathlib_name.py
print(f'stem : {p.stem}') # pathlib_name
print(f'suffix: {p.suffix}') # .py
# joining paths, as simple as:
p = Path("segment_one", "segment_two", "segment_three")
"segment_one/segment_two/segment_three"
# or even simpler:
\!h pathlib.Path.home() / 'python' / 'scripts' / 'test.py'
# gives: PosixPath('/home/gahjelle/python/scripts/test.py')
# renaming file
p.rename("new_name.rst")
# reading from file
\!h content = p.read_text()
# pathlib supports many more things, like
# Manipulating Directories and Symbolic Links
# File Types & File Properties & File Permissions
\!h Directories and files can be deleted using .rmdir() and .unlink() respectively. (Again, be careful!)