Python OS Module Tutorial and Examples

Python OS Module Tutorial and Examples

To interact with the file system or to deal with filenames, paths, directories we use python os module.

in this blog post i will show you some of the important functions in python os module.

  • os.getcwd()
  • os.chdir()
  • os.mkdir()
  • os.listdir()
  • os.rename()
  • os.rmdir()

os.getcwd()

this module is used get  or print the current working directory.

import os
x=os.getcwd()
print(x)

This will print the current working directory, Where this python script file located.

os.chdir()

this function is used to change the current working directory.

os.mkdir()

this module is used to create a new directory

import os
os.mkdir("devops")

this will create a directory called devops

os.listdir()

this module is used to list all files and directories names in a particular  directory

import os
x=os.listdir()
print(x)

this will list or print all the files and directory names in a current directory.

list files and directories  in a particular directory

import os
x=os.listdir(r"C:\Users\devops\Desktop\pycharm")
print(x)

this will print all the files and directory names in a "C:\Users\devops\Desktop\pycharm" directory.

os.rename()

os.rename() is used to rename a file or directory name.

import os 
os.rename("asf.txt","devops.txt")

this will rename asf.txt into devops.txt

import os 
os.rename("devops","python")

this will rename a directory called devops into python.

so using this module we can rename a file to another file name and we can rename a directory into another directory.

os.rmdir()

this module is used to delete a directory.

import os
os.rmdir("devops")

this will remove a directory called devops.

  • Python OS Module Tutorial and Examples
  • python os module
  • python os module examples
  • Python OS Module Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *