OS Module - Python

OS Module in Python


For a better reading experience, check the published document


Importing the module

from os import *

Most commonly used commands

Directory info

# returns a list of all the files and folders in the given directory
# (r) is used to treat the string as a row string so it doesn't activate 
# any of the escape charachters after the slashes 
listdir(r"assets/photos") 


# returns a list of all the files and folders in the current directory
listdir(".")


# change the directory to the given one
chdir(r"G:/project1/assets/photos")


# returns the current work directory
getcwd()


# det the loged in user name in this terminal 
getlogi

Directory manipulation

# execute the command (pip install numpy) in a subshell
system("pip install numpy")


# open the file 
open(r"G:\Files\Basics.docx")


# create a new folder in the current dir
mkdir("myFolder") 


# create a new folder and all directories needed to contain the leaf directory
mkdirs("myFolder/project1/test")


# rename the file or the folder 
# but we have to be on their dir or open it with (chdir)
rename("old name", "new name") 


# deletes the file
remove("myFile.txt") 


# deletes the folder 
rmdir("myFol

The os.path class 

# split the name contents (name="photo") and (exe=".png")
name, exe = path.splitext("photo.png")


# check if there is a folder with that name in the current directory
path.exists("myFolder")


# returns the dir name (G:\Files)
path.dirname(r"G:\Files\Basics.docx")


# check if the given input is a directory
path.isdir("G:\Files") 


# check if the given input is a file
path.isfile("G:\Files\Basics.docx")  


# check if the input is a link
path.islink("G:\Files\Basics.docx")


# returns the size of the file in bytes
path.getsize(r"G:\Files\Basics.d

Comments