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

  • 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!

7.1.5. Script Path

  • Returns an absolute path to currently running script

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

7.1.6. Convert Relative Path to Absolute

  • os.path.join() - adds OS dependent directory separator

  • os.path.dirname() - gets the absolute path of the argument

from os.path import dirname, join


dirname(__file__)
# /home/python/

join(dirname(__file__), 'myfile.txt')
# /home/python/myfile.txt