Module OS in Python

 

Module OS in Python


module OS needs to be import for the same


  • How to create directory.  os.makedirs("directory_name")
Example :
    • if directory does not exist, it will create directory

#program

import os
os.makedirs(
"Sample_Directory")
print("Directory Sample_Directory created successfully")

 #output

Directory Sample_Directory created successfully


    • if directory already exist, it will throw File_Exists_Error

#program

import os
os.makedirs(
"Sample_Directory")
print("Directory Sample_Directory created successfully")

 #output

Traceback (most recent call last):
File "
C:/Self_Practice_Er_M_S_Dandyan/Python/Pycharm/xml/main.py", line 4, in <module>
os.makedirs("Sample_Directory")
FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'Sample_Directory'




  • How to get current directory path.   os.getcwd()

#program

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

 #output

C:\Self_Practice_Er_M_S_Dandyan\Python\Pycharm\xml


  • How to check directory / file exists of not.   os.path.exists(directory/ file name)
    • if directory or file exists, path.exists will return True
    • if directory or file does not exists, path.exists will return False

#program

import os
Exist = os.path.exists(
"Sample_Directory")
print("Sample_Directory Exist : ", Exist)

Exist = os.path.exists(
"Sample_Directory/file.txt")
print("Sample_Directory/file.txt Exists : ", Exist)

 #output

Sample_Directory Exist : True
Sample_Directory/file.txt Exists : False



  • How to delete directory.   os.rmdir(directory_name)
 
#program

import os
Exist = os.path.exists(
"Sample_Directory")
print("Sample_Directory Exist : ", Exist)

os.rmdir(
"Sample_Directory")
Exist = os.path.exists(
"Sample_Directory")
print("Sample_Directory Exist : ", Exist)
if Exist == False :
print("directory deleted succesfully")

#output

Sample_Directory Exist : True
Sample_Directory Exist : False
directory deleted succesfully



  • How to delete file.     os.remove("file_name")

#program

import os
Exist = os.path.exists(
"my_file.txt")
print("my_file.txt Exist : ", Exist)

os.remove(
"my_file.txt")
Exist = os.path.exists(
"my_file.txt")
print("my_file.txt Exist : ", Exist)
if Exist == False :
print("my_file.txt deleted successfully")

 #output

my_file.txt Exist : True
my_file.txt Exist : False
my_file.txt deleted successfully






Comments

My photo
Techno Xpresss
Bangalore, Karnataka, India