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.
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)))
In [3]:
for path in PATHS:
print('{!r:>17}:{}'.format(path, os.path.basename(path)))
In [4]:
for path in PATHS:
print('{!r:>17}:{}'.format(path, os.path.dirname(path)))
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)))
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))
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))
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)))
In [10]:
import os.path
for user in ['', 'gaufung', 'nosuchuser']:
lookup = '~' + user
print('{!r:>15} : {!r}'.format(
lookup, os.path.expanduser(lookup)))
In [11]:
import os.path
import os
os.environ['MYVAR'] = 'VALUE'
print(os.path.expandvars('/path/to/$MYVAR'))
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)))
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)))
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'))