Python File Directory

A Python directory or folder is a collection of files and sub directories. Python has the os module, which provides us with many useful methods to work with directories (and files as well).

Get Current Directory

We can get the present working directory using the getcwd() method.

This method returns the current working directory in the form of a string. We can also use the getcwdb() method to get it as bytes object.

>>> import os
>>> os.getcwd()
>>> os.getcwdb()

The extra backslash implies escape sequence. The print() function will render this properly.

>>> print(os.getcwd())

Changing Directory

We can change the current working directory using the chdir() method.

The new path that we want to change to must be supplied as a string to this method. We can use both forward slash (/) or the backward slash (\) to separate path elements.

It is safer to use escape sequence when using the backward slash.

>>> import os
>>> path = 'C:\\Users\\OM SAI RAM\\AppData\\Local\\Programs\\Python\\Python36-32'
>>> # Check current working directory.
>>> retval = os.getcwd()
>> print ("Current working directory is : %s" % retval)
Current working directory is : C:\Users\OM SAI RAM\AppData\Local\Programs\Python\Python36-32
>>> # Now change the directory
>>> os.chdir( path )
>>> # Check current working directory.
>>> retval = os.getcwd()
>>> print ("Directory changed successfully : %s" % retval)
Directory changed successfully : C:\Users\OM SAI RAM\AppData\Local\Programs\Python\Python36-32

Making a New Directory

We can make a new directory using the mkdir() method.

This method takes in the path of the new directory. If the full path is not specified, the new directory is created in the current working directory.

>>> os.mkdir('test')
>>> os.listdir()
['DLLs', 'Doc', 'include', 'Lib', 'libs', 
'LICENSE.txt', 'My_Programs', 'NEWS.txt', 
'python.exe', 'python3.dll', 'python36.dll', 
'pythonw.exe', 'tcl', 'test', 'Tools', 

Removing Directory or File

The method rmdir() removes the directory path. It works only when the directory is empty, else OSError is raised./p>

Syntax :
Example :
>>> os.listdir()
['new_one', 'My_TEXT.txt']

>>> os.remove('My_TEXT.txt')
>>> os.listdir()

>>> os.rmdir('new_one')
>>> os.listdir()