It is possible to automatically perform many operating system tasks. The OS module in Python provides functions for creating and removing a directory (folder), fetching its contents, changing and identifying the current directory, etc.
You first need to import the os module to interact with the underlying operating system. So, import it using the import os statement before using its functions.
Getting Current Working Directory
The getcwd() function confirms returns the current working directory.
>>> import os
>>> os.getcwd()
'C:\\Python37'
Creating a Directory
We can create a new directory using the os.mkdir() function
>>> import os
>>> os.mkdir("C:\MyPythonProject")
Changing the Current Working Directory
We must first change the current working directory to a newly created one before doing any operations in it. This is done using the chdir() function.
>>> import os
>>> os.chdir("C:\MyPythonProject") # changing current workign directory
>>> os.getcwd()
'C:\MyPythonProject'
Removing a Directory
The rmdir() function in the OS module removes the specified directory either with an absolute or relative path.
>>> import os
>>> os.rmdir("C:\\MyPythonProject")
List Files and Sub-directories
The listdir() function returns the list of all files and directories in the specified directory.
>>> import os
>>> os.listdir("c:\python37")
['DLLs', 'Doc', 'fantasy-1.py', 'fantasy.db', 'fantasy.py', 'frame.py',
'gridexample.py', 'include', 'Lib', 'libs', 'LICENSE.txt', 'listbox.py', 'NEWS.txt',
'place.py', 'players.db', 'python.exe', 'python3.dll', 'python36.dll', 'pythonw.exe',
'sclst.py', 'Scripts', 'tcl', 'test.py', 'Tools', 'tooltip.py', 'vcruntime140.dll',
'virat.jpg', 'virat.py']
Top comments (0)