os.path

Writing code to work with files on multiple platforms is easy using the functions included in the os.path module. Even programs not intended to be ported between platforms should use os.path for reliable filename parsing.

Parsing Path


In [1]:
import os.path

PATHS = [
    '/one/two/three',
    '/one/two/three/',
    '/',
    '.',
    '',
]

for path in PATHS:
    print('{!r:>17} : {}'.format(path, os.path.split(path)))


 '/one/two/three' : ('/one/two', 'three')
'/one/two/three/' : ('/one/two/three', '')
              '/' : ('/', '')
              '.' : ('', '.')
               '' : ('', '')

In [3]:
for path in PATHS:
    print('{!r:>17}:{}'.format(path, os.path.basename(path)))


 '/one/two/three':three
'/one/two/three/':
              '/':
              '.':.
               '':

In [4]:
for path in PATHS:
    print('{!r:>17}:{}'.format(path, os.path.dirname(path)))


 '/one/two/three':/one/two
'/one/two/three/':/one/two/three
              '/':/
              '.':
               '':

In [5]:
import os.path

PATHS = [
    'filename.txt',
    'filename',
    '/path/to/filename.txt',
    '/',
    '',
    'my-archive.tar.gz',
    'no-extension.',
]

for path in PATHS:
    print('{!r:>21} : {!r}'.format(path, os.path.splitext(path)))


       'filename.txt' : ('filename', '.txt')
           'filename' : ('filename', '')
'/path/to/filename.txt' : ('/path/to/filename', '.txt')
                  '/' : ('/', '')
                   '' : ('', '')
  'my-archive.tar.gz' : ('my-archive.tar', '.gz')
      'no-extension.' : ('no-extension', '.')

In [6]:
import os.path

paths = ['/one/two/three/four',
         '/one/two/threefold',
         '/one/two/three/',
         ]
for path in paths:
    print('PATH:', path)

print()
print('PREFIX:', os.path.commonprefix(paths))


PATH: /one/two/three/four
PATH: /one/two/threefold
PATH: /one/two/three/

PREFIX: /one/two/three

In [7]:
import os.path

paths = ['/one/two/three/four',
         '/one/two/threefold',
         '/one/two/three/',
         ]
for path in paths:
    print('PATH:', path)

print()
print('PREFIX:', os.path.commonpath(paths))


PATH: /one/two/three/four
PATH: /one/two/threefold
PATH: /one/two/three/

PREFIX: /one/two

Building Path

If any argument to join begins with os.sep, all of the previous arguments are discarded and the new one becomes the beginning of the return value.


In [8]:
import os.path

PATHS = [
    ('one', 'two', 'three'),
    ('/', 'one', 'two', 'three'),
    ('/one', '/two', '/three'),
]

for parts in PATHS:
    print('{} : {!r}'.format(parts, os.path.join(*parts)))


('one', 'two', 'three') : 'one/two/three'
('/', 'one', 'two', 'three') : '/one/two/three'
('/one', '/two', '/three') : '/three'

In [10]:
import os.path

for user in ['', 'gaufung', 'nosuchuser']:
    lookup = '~' + user
    print('{!r:>15} : {!r}'.format(
        lookup, os.path.expanduser(lookup)))


            '~' : '/Users/gaufung'
     '~gaufung' : '/Users/gaufung'
  '~nosuchuser' : '~nosuchuser'

In [11]:
import os.path
import os

os.environ['MYVAR'] = 'VALUE'

print(os.path.expandvars('/path/to/$MYVAR'))


/path/to/VALUE

Normal Path


In [12]:
import os.path

PATHS = [
    'one//two//three',
    'one/./two/./three',
    'one/../alt/two/three',
]

for path in PATHS:
    print('{!r:>22} : {!r}'.format(path, os.path.normpath(path)))


     'one//two//three' : 'one/two/three'
   'one/./two/./three' : 'one/two/three'
'one/../alt/two/three' : 'alt/two/three'

In [13]:
import os
import os.path

os.chdir('/usr')

PATHS = [
    '.',
    '..',
    './one/two/three',
    '../one/two/three',
]

for path in PATHS:
    print('{!r:>21} : {!r}'.format(path, os.path.abspath(path)))


                  '.' : '/usr'
                 '..' : '/'
    './one/two/three' : '/usr/one/two/three'
   '../one/two/three' : '/one/two/three'

File Time


In [20]:
import os.path
import time

print('File         :', '~/WorkSpace/PythonStandardLibrary/FileSystem/Path.ipynb')
print('Access time  :', time.ctime(os.path.getatime('/Users/gaufung/WorkSpace/PythonStandardLibrary/FileSystem/Path.ipynb')))
print('Modified time:', time.ctime(os.path.getmtime('/Users/gaufung/WorkSpace/PythonStandardLibrary/FileSystem/Path.ipynb')))
print('Change time  :', time.ctime(os.path.getctime('/Users/gaufung/WorkSpace/PythonStandardLibrary/FileSystem/Path.ipynb')))
print('Size         :', os.path.getsize('/Users/gaufung/WorkSpace/PythonStandardLibrary/FileSystem/Path.ipynb'))


File         : ~/WorkSpace/PythonStandardLibrary/FileSystem/Path.ipynb
Access time  : Mon Sep  4 14:02:38 2017
Modified time: Mon Sep  4 14:02:38 2017
Change time  : Mon Sep  4 14:02:38 2017
Size         : 9833