Scripting >> Python >> Examples >> Input Output >>  How to use os.path module to manipulate file directories paths in the Operating System

 

Get current directory

>>> import os

>>> os.getcwd()  # get as a string
'C:\Program Files\PyScripter'

>>> print(os.getcwd())
C:\Program Files\PyScripter

>>> os.getcwdb() # get as byte object
b'C:\Program Files\PyScripter'

Changing directory >>> os.chdir('C:\Python33')

>>> print(os.getcwd())
C:\Python33
Listing a directory >>> print(os.getcwd())
C:\Python33

>>> os.listdir()
['DLLs',
'Doc',
'include',
'Lib',
'libs',
'LICENSE.txt',
'NEWS.txt',
'python.exe',
'pythonw.exe',
'README.txt',
'Scripts',
'tcl',
'Tools']

>>> os.listdir('G:\')
['$RECYCLE.BIN',
'Movies',
'Music',
'Photos',
'Series',
'System Volume Information']
Make new directory  >>> os.mkdir('test')

>>> os.listdir()
['test']
Rename a directory >>> os.listdir()
['test']

>>> os.rename('test','new_one')

>>> os.listdir()
['new_one']
 Removing a (empty) directory or file >>> os.listdir()
['new_one', 'old.txt']

>>> os.remove('old.txt')
>>> os.listdir()
['new_one']

>>> os.rmdir('new_one')
>>> os.listdir()
[]
Removing non empty directory >>> os.listdir()
['test']

>>> os.rmdir('test')
Traceback (most recent call last):
...
OSError: [WinError 145] The directory is not empty: 'test'

>>> import shutil

>>> shutil.rmtree('test')
>>> os.listdir()
[]
Get the basename of a full path >>> import os
>>> os.getcwd()
'C:\Program Files\Microsoft Office'
>>> os.path.basename(os.getcwd())
'Microsoft Office'
>>>
Splits a file path to its name and extension parts

 >>> import os
>>> os.path.splitext("C:\Program Files\Microsoft Office\Office12\VISSHE.DLL")
('C:\Program Files\Microsoft Office\Office12\VISSHE', '.DLL')

>>> os.path.splitext("notepad.exe")
('notepad', '.exe')

returns a list of [name,extension]

Splits a full path to its directory and filename

>>> os.path.split("C:\Program Files\Microsoft Office\Office12\VISSHE.DLL")
('C:\Program Files\Microsoft Office\Office12', 'VISSHE.DLL')

>>> os.path.split('/etc/hosts.deny')
('/etc', 'hosts.deny')


>>> os.path.split('/etc/ssh/')
('/etc/ssh', '')
 

>>> os.path.split('/etc/ssh')
('/etc', 'ssh')

Split the pathname path into a pair, (head, tail) where tail is the last pathname component and head is everything leading up to that. The tail part will never contain a slash; if path ends in a slash, tail will be empty

Test for dir

Windows example

>>> import os
>>> os.path.isdir("C:\Program Files\Microsoft Office\Office12")
True
>>> os.path.isdir("C:\Program Files\Microsoft Office\Office12\VISSHE.DLL")
False

Unix example

>>> import os
>>> os.path.isdir('/etc')
True
>>> os.path.isdir('/etc/hosts')
False
 

 Test for file  
Windows example

>>> import os
>>> os.path.isfile("C:\Program Files\Microsoft Office\Office12")
False
>>> os.path.isfile("C:\Program Files\Microsoft Office\Office12\VISSHE.DLL")
True

Unix example

>>> import os
>>> os.path.isfile('/etc')
False
>>> os.path.isfile('/etc/hosts')
True