13.1. File Path Relative¶
Python works with both relative and absolute path
Path is relative to currently running script
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 sameRelative paths works the same on Windows and
*nix
(Linux, macOS, BSD, etc.)
13.1.1. Current Directory¶
Path is relative to currently running script
.
- Current directory
>>> FILE = 'myfile.txt'
>>> FILE = 'data/myfile.txt'
>>> FILE = './myfile.txt'
>>> FILE = './data/myfile.txt'
13.1.2. Upper Directory¶
Path is relative to currently running script
..
- Parent directory
>>> FILE = '../myfile.txt'
>>> FILE = '../data/myfile.txt'
>>> FILE = '../../myfile.txt'
>>> FILE = '../../data/myfile.txt'
13.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 = 'myfile.txt'
>>> FILES = [
... 'myfile.txt',
... 'myfile.csv',
... ]