10.7. Pathlib Files

10.7.1. SetUp

>>> from pathlib import Path

10.7.2. Define Path

>>> myfile = Path('/tmp/myfile.txt')

10.7.3. Touch

  • If file does not exist, it will be created.

  • If file exists, it will update the last modified time.

>>> myfile = Path('/tmp/myfile.txt')
>>> myfile.touch()

10.7.5. Use Case - 1

>>> FILE = '/tmp/mydir/myfile.txt'
>>> with open(FILE) as file:
...     content = file.read()
>>> FILE = Path('/tmp/mydir/myfile.txt')
>>> with open(FILE) as file:
...     content = file.read()
>>> file = Path('/tmp/mydir/myfile.txt')
>>> result = file.read_text()

10.7.6. Use Case - 2

>>> from itertools import chain
>>>
>>>
>>> mydir = Path('/tmp/mydir')
>>> files = chain(
...     mydir.rglob('*.txt'),
...     mydir.rglob('*.html'),
... )
>>>
>>> for file in sorted(files):
...     print(file)
...
/tmp/mydir/myfile1.txt
/tmp/mydir/myfile2.txt

10.7.7. Use Case - 3

>>> directories = [
...     '/tmp/mydir',
...     '/tmp/newdir',
...     '/tmp/otherdir',
... ]
>>> for directory in map(Path, directories):
...     print(directory.exists())
...
True
False
False
>>> for directory in map(Path, directories):
...     for file in directory.rglob('*.txt'):
...         print(file)
...
/tmp/mydir/myfile.txt

10.7.8. Use Case - 3

>>> directories = [
...     Path('/tmp/mydir'),
...     Path('/tmp/newdir'),
...     Path('/tmp/otherdir'),
... ]
>>>
>>> for directory in directories:
...     directory.exists()
...
True
False
False

10.7.9. Assignments

# %% About
# - Name: File Path Abspath
# - Difficulty: easy
# - Lines: 3
# - Minutes: 2

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Define `abspath` with converted `filename` to absolute path
# 2. To `result` assign string:
#    - `file` if path is a file
#    - `directory` if path is a directory
#    - `missing` if path does not exist
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj `abspath` z przekonwertowanym `filename` do ścieżki bezwzględnej
# 2. Do `result` przypisz ciąg znaków:
#    - `file` jeżeli ścieżka jest plikiem
#    - `directory` jeżeli ścieżka jest katalogiem
#    - `missing` jeżeli ścieżka nie istnieje
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `from pathlib import Path`
# - `Path.cwd()`
# - `Path()`
# - `Path.is_dir()`
# - `Path.is_file()`
# - `Path.exists()`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0

>>> assert sys.version_info >= (3, 9), \
'Python has an is invalid version; expected: `3.9` or newer.'

>>> assert isinstance(result, str), \
'Result must be a str with: `file`, `directory` or `missing`'

>>> assert isinstance(abspath, Path), \
'Use Path class from pathlib library to create a filepath'

>>> current_directory = Path.cwd()
>>> assert str(current_directory) in str(abspath), \
'File Path must be absolute, check if you have current directory in path'

>>> result
'missing'
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -v myfile.py`

# %% Imports
from pathlib import Path

# %% Types
abspath: Path
result: str

# %% Data
FILENAME = 'myfile.txt'

# %% Result
abspath = ...
result = ...