11.1. Pathlib About
Python works with both relative and absolute path
Path separator
\
(backslash) is used on WindowsPath 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
11.1.1. Relative Paths
Path is relative to currently running script
.
- Current directory..
- Parent directory
Current directory:
>>> FILE = 'myfile.txt'
>>> FILE = './myfile.txt'
>>> FILE = 'data/myfile.txt'
>>> FILE = './data/myfile.txt'
Parent directory:
>>> FILE = '../myfile.txt'
>>> FILE = '../data/myfile.txt'
>>> FILE = '../../myfile.txt'
>>> FILE = '../../data/myfile.txt'
11.1.2. Absolute Path
Absolute path on Windows starts with drive letter
Absolute path on
*nix
starts with root/
dirAbsolute 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'
11.1.3. Good Practices
Never hardcode paths, use constant as a file name or file path
Convention (singular form):
FILE
,FILENAME
,FILEPATH
,PATH
Convention (plural form):
FILES
,FILENAMES
,FILEPATHS
,PATHS
Note, that
PATH
is usually used for other purposes (sys.path
oros.getenv('PATH')
)
>>> FILE = '/tmp/myfile.txt'
>>> FILES = [
... '/tmp/myfile.txt',
... '/tmp/myfile.csv',
... ]
11.1.4. Escaping Characters
"\ " (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