7.1. File Path

7.1.1. Rationale

  • Never hardcode paths (put path directly to open function)

  • Use constant as a file name or file path

  • Convention FILE, FILENAME, FILEPATH, PATH

  • Or their respective plural forms for multiple files

  • Note, that PATH is usually used for other purposes (sys.path or os.getenv('PATH'))

  • Always use raw-strings r"..."

  • Paths on Windows uses \

  • Paths on *nix uses /

  • *nix operating systems: Linux, macOS, BSD and other POSIX compliant OSes (excluding Windows)

  • In newer Windows versions both \ and / works

7.1.2. 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

FILE = r'C:\Users\Watney\myfile.txt'
FILE = r'/tmp/myfile.txt'

7.1.3. Relative Path

  • Path is relative to currently running script

  • . - Current directory

  • .. - Parent directory

FILE = r'myfile.txt'
FILE = r'./myfile.txt'

FILE = r'tmp/myfile.txt'
FILE = r'./tmp/myfile.txt'

FILE = r'../myfile.txt'
FILE = r'../tmp/myfile.txt'

FILE = r'../../myfile.txt'
FILE = r'../../tmp/myfile.txt'

7.1.4. Escaping Characters in Path

  • "\ " (slash space) - escapes space

  • Note escapes are not needed

FILE = '/tmp/my file.txt'

with open(FILE) as file:
    print(file.read())

# Success!
FILE = r'/tmp/my file.txt'

with open(FILE) as file:
    print(file.read())

# Success!
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

7.1.5. Create Directories

from os import mkdir


mkdir('/tmp/a')
# directory /tmp/a created

mkdir('/tmp/a/b/c')
# FileNotFoundError: [Errno 2] No such file or directory: '/tmp/a/b/c'
from os import makedirs


makedirs('/tmp/a')
# directory /tmp/a created

makedirs('/tmp/a')
# FileExistsError: [Errno 17] File exists: '/tmp/a'

makedirs('/tmp/a', exist_ok=True)
# No error

makedirs('/tmp/a/b/c')
# directory /tmp/a/b/c created

7.1.6. Exists and is Directory or File

from pathlib import Path


path = Path(r'/tmp/myfile.txt')

path.exists()
# True

path.is_dir()
# False

path.is_file()
# True

7.1.7. Current Working Directory

  • Returns an absolute path to current working directory

from pathlib import Path

Path.cwd()
# PosixPath('/home/python/')

7.1.8. Convert Relative Path to Absolute

from pathlib import Path


Path(Path.cwd(), 'myfile.txt')
# PosixPath('/home/python/myfile.txt')

7.1.9. Script Path

  • Returns an absolute path to currently running script

print(__file__)
# /home/python/myscript.py

7.1.10. Assignments

7.1.10.1. File Path Abspath

English
  1. Using input() ask user for a file path

  2. Convert path to absolute

  3. Print if path exists and leads to file or directory

Polish
  1. Używając input() zapytaj użytkownika o ścieżkę do pliku

  2. Przekonwertuj ścieżkę do bezwzględnej

  3. Wypisz czy ścieżka istnieje i czy prowadzi do pliku czy katalogu