12.2. File Path Absolute

  • Python works with both relative and absolute path

  • Path separator \ (backslash) is used on Windows

  • Path separator / (slash) is used on *nix operating systems: Linux, macOS, BSD and other POSIX compliant OSes (excluding older versions of Windows)

  • In newer Windows versions both \ and / works the same

12.2.1. Absolute Path

  • Absolute path on Windows starts with drive letter

  • Absolute path on *nix starts with root / dir

  • Absolute path include all entries in the directories hierarchy

Path on Linux:

>>> FILE = r'/home/mwatney/myfile.txt'

Path on macOS:

>>> FILE = r'/Users/mwatney/myfile.txt'

Path on Windows:

>>> FILE = 'C:\\Users\\mwatney\\myfile.txt'

12.2.2. Escaping Characters in Path

  • "\ " (backslash space) - escapes space

  • Note that in Python escapes in paths are not required

>>> FILE = '/tmp/my file.txt'
>>> FILE = r'/tmp/my file.txt'
>>> FILE = r'C:\Users\Admin\myfile.txt'
>>>
>>>
>>> repr(FILE)
"'C:\\\\Users\\\\Admin\\\\myfile.txt'"
>>>
>>> str(FILE)
'C:\\Users\\Admin\\myfile.txt'
>>>
>>> print(repr(FILE))
'C:\\Users\\Admin\\myfile.txt'
>>>
>>> print(FILE)
C:\Users\Admin\myfile.txt

12.2.3. Convert Relative Path to Absolute

>>> from pathlib import Path
>>>
>>>
>>> file = Path('myfile.txt')
>>> file.absolute()  
/home/watney/myfile.txt

12.2.4. Dirname, Filename

>>> from pathlib import Path
>>>
>>>
>>> file = Path('/home/watney/myfile.py')
>>>
>>> print(file.parent)
/home/watney
>>>
>>> print(file.name)
myfile.py

12.2.5. Script Path

  • __file__ - Returns an absolute path to currently running script

>>> print(__file__)  
/home/watney/myscript.py
>>> from pathlib import Path
>>>
>>>
>>> file = Path(__file__)  
>>>
>>> print(file.parent)  
/home/watney
>>>
>>> print(file.name)  
myfile.py

12.2.6. Assignments

Code 12.10. Solution
"""
* Assignment: File Path Exception
* Type: class assignment
* Complexity: easy
* Lines of code: 6 lines
* Time: 3 min

English:
    1. Modify `check` function
    2. If `filename` exists, return 'Ok'
    3. If `filename` does not exist, return 'File not found'
    4. Use `Path` from `pathlib`
    5. Run doctests - all must succeed

Polish:
    1. Zmodyfikuj funkcję `check`
    2. Jeżeli `filename` istnieje, zwróć 'Ok'
    3. Jeżeli `filename` nie istnieje, zwróć 'File not found'
    4. Użyj `Path` z `pathlib`
    5. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from inspect import isfunction

    >>> assert check is not Ellipsis, \
    'Assign your result to function `check`'

    >>> assert isfunction(check), \
    'Object `check` has invalid type, should be a function'

    >>> check(__file__)
    'Ok'

    >>> check('_notexisting.txt')
    'File not found'
"""

from pathlib import Path

# Modify `result` function
# If `filename` exists, return 'Ok'
# If `filename` does not exist, return 'File not found'
# Use `Path` from `pathlib`
# type: Callable[[str], str]
def check(filename: str) -> str:
    ...


Code 12.11. Solution
# TODO: exists()
# TODO: is_file()
# TODO: is_dir()
# TODO: is_symlink()

"""
* Assignment: File Path Abspath
* Type: class assignment
* Complexity: easy
* Lines of code: 3 lines
* Time: 5 min

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

Polish:
    1. Zdefiniuj `path` z przekonwertowym `filename` do ścieżki bezwzględnej
    2. Do `result` przypisz ciąg znaków:
        a. `file` jeżeli ścieżka jest plikiem
        b. `directory` jeżeli ścieżka jest katalogiem
        c. `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()`

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> 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'
"""

from pathlib import Path


FILENAME = 'myfile.txt'

# Absolute path to FILENAME
# type: Path
abspath = ...

# File, directory or missing
# type: str
result = ...