Python os Module – Complete Guide With Practical Examples
The os module in Python is one of the most powerful modules used to interact with the operating system. It allows you to perform operations such as:
- Create new directories
- Change working directory
- Delete files and folders
- Rename files
- Walk through directories
- Get file size, metadata
- List files & folders
This module gives Python the ability to perform real system-level tasks similar to Windows Explorer or Linux Shell.
Basic OS Module Program (Step-by-Step Explanation)
import os
# Create a folder
# os.mkdir("hello")
# Change directory
os.chdir("hello")
# Create a file inside the folder
f = open("hello1.txt", "w")
f.write("hello world")
f.close()
# Delete the file
os.remove("hello1.txt")
# Remove directory (if empty)
# os.rmdir("hello1")
# Print current working directory
print(os.getcwd())
# List all files in current directory
print(os.listdir())
# Print all files from a specific directory
location = 'd:/c/'
for file in os.listdir(location):
# if file.endswith(".c"):
print(os.path.join(location, file))
Important OS Module Functions You Must Know
1. os.mkdir("folder") – Create directory
2. os.rmdir("folder") – Remove directory (must be empty)
3. os.remove("file") – Delete file
4. os.rename(old, new) – Rename a file or folder
5. os.listdir(path) – List everything inside folder
6. os.getcwd() – Get current working directory
7. os.chdir(path) – Change working directory
8. os.walk(path) – Traverse all folders & subfolders
These functions are commonly used in file automation, cleaning scripts, backup scripts, and data mining tasks.
Advanced Example – Count Files, Images, Videos, Python Programs & Largest File
The following program scans your entire drive (D:/ in this example) and counts:
- Total images
- Total text/doc files
- Total video files
- Total Python files
- Finds the largest file in the drive
import os
imgcount = 0
txtcount = 0
videocount = 0
pythonpgrm = 0
directory = 'd:/'
maxsize = 0
maxfilepath = ''
for root, dirs, files in os.walk(directory):
for file in files:
path = os.path.join(root, file)
size = os.stat(path).st_size
# Find largest file
if maxsize < size:
maxsize = size
maxfilepath = path
# Count image files
if file.endswith('.png') or file.endswith('.jpg'):
imgcount += 1
# Count text and doc files
elif file.endswith('.txt') or file.endswith('.docx'):
txtcount += 1
# Count audio/video files
elif file.endswith('.mp3') or file.endswith('.mp4'):
videocount += 1
# Count python files
elif file.endswith('.py'):
pythonpgrm += 1
print("****** Scan Result for D Drive ******")
print("Total images : " + str(imgcount))
print("Total text/docs : " + str(txtcount))
print("Total video files : " + str(videocount))
print("Total Python files : " + str(pythonpgrm))
print("Largest file path : " + maxfilepath)
print("Largest file size : " + str(maxsize) + " bytes")
Extra Concepts Added for Better Understanding
1. Creating Nested Folders
os.makedirs("parent/child/grandchild")
2. Checking if a File Exists
import os
if os.path.exists("demo.txt"):
print("File found")
else:
print("File not found")
3. Getting File Size in KB / MB
size = os.stat("demo.txt").st_size
print(size/1024, "KB")
print(size/(1024*1024), "MB")
4. Rename Multiple Files Automatically
import os
for i, file in enumerate(os.listdir()):
os.rename(file, f"image_{i}.jpg")
5. Searching for Files by Extension
import os
directory = "d:/"
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith(".pdf"):
print(os.path.join(root, file))
Assignments for OS Module
- Count all folders in a drive.
- Find the maximum size folder (not file).
- Count total images in a specific directory.
- Count all Python files in the entire computer.
- Create a program to back up all .txt files to another folder.
- Create an automatic renaming script for images.
8 Comments
Q:- WAP to count total folder in the drive ?
ReplyDeleteSolution: -
import os
print("The Total Number of Folder's are available in Given Path are : -")
print(len(os.listdir('C:/')))
import os
ReplyDeletefrom pathlib import Path
def endswith1(s):
if s.index('.')>=0:
return s[s.index('.'):]
else:
return s
imgcount=0
txtcount=0
entries = Path('d:/')
for entry in entries.iterdir():
print(entry.name)
for entry1 in entry.iterdir():
print(entry1.name)
try:
if endswith1(entry1.name)=='png' or endswith1(entry1.name)=='jpg' or endswith1(entry1.name)=='gif':
imgcount = imgcount+1
elif endswith1(entry1.name)==".txt" or endswith1(entry1.name)==".doc":
txtcount = txtcount+1
except:
pass
print("Total images are "+str(imgcount))
print("Total text files are "+str(txtcount))
import os
ReplyDeletefrom pathlib import Path
def endswith1(s):
if s.index('.')>=0:
return s[s.index('.'):]
else:
return s
imgcount=0
txtcount=0
entries = Path('d:/hello')
for entry in entries.iterdir():
print(entry.name)
if os.path.isdir(entry.name):
for entry1 in entry.iterdir():
print(entry1.name)
try:
if endswith1(entry1.name)=='png' or endswith1(entry1.name)=='jpg' or endswith1(entry1.name)=='gif':
imgcount = imgcount+1
elif endswith1(entry1.name)==".txt" or endswith1(entry1.name)==".doc":
txtcount = txtcount+1
except:
pass
else:
if endswith1(entry.name)=='png' or endswith1(entry.name)=='jpg' or endswith1(entry.name)=='gif':
imgcount = imgcount+1
elif endswith1(entry.name)==".txt" or endswith1(entry.name)==".doc":
txtcount = txtcount+1
print("Total images are "+str(imgcount))
print("Total text files are "+str(txtcount))
Ankit Saxena
ReplyDeleteimport os
path = input("Enter your directory path: ")
if os.path.isfile(path):
print(f"The given path {path} is a file. please pass only directory path")
else:
all_file = os.listdir(path)
if len(all_file)==0:
print(f"The given path is {path} an empty path")
else:
extension=input("Enter the required files extention .py/ .gif /.docx .txt / .jpg ./.pptx: ")
req_files = []
for x in all_file:
if x.endswith(extension):
req_files.append(x)
if len(req_files)==0:
print(f"There are no {extension} files in the logcation of {path}")
else:
print(f"There are {len(req_files)} files in the location of {path} with an extention of {extension}")
print(f"The files are: {req_files}")
#WAP to count total folder in the computer, drive, max size folder, total image for the particular director, total video on the directory, total python program in the computer.
ReplyDeleteimport os
imgcount=0
txtcount=0
videocount=0
pythonpgrm=0
directory= 'c:/'
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith('.png' )or file.endswith('.jpg') :#total image 5825
imgcount = imgcount+1
elif file.endswith('.txt' )or file.endswith('.docx') : # total File 1492
txtcount = txtcount+1
elif file.endswith('.mp3') or file.endswith('.mp4'): #total video 14
videocount=videocount+1
elif file.endswith('.py') : #total python program 238 + compiled file 1754 =1992
pythonpgrm=pythonpgrm+1
try:
objects = os.listdir("c:")
a=0
name = ""
for item in objects:
size = os.path.getsize(item)
if size > a:
a = size
name = item
print "Largest file is "+name+ " at "+str(a) + " bytes"
print(a, 'bytes')
except WindowsError:
print("$RECYCLE.BIN not specified")
print("******In C Drive****** ")
print("Total images are "+str(imgcount))
print("Total text files are "+str(txtcount))
print("Total Video files are "+str(videocount))
print("Total Python Program are "+str(pythonpgrm))
#ABHISHEK SINGH
ReplyDelete#Finding Image/Video/Python Files based on choice
import os
def extension(s):
s1=""
for i in range(len(s)-1,0,-1):
if s[i]=='.':
break
for j in range(i,len(s)):
s1+=s[j]
return s1
print('''Menu:
1)Press 1 to view file of specific Drive / Path
2)Press 2 to view ALL FILES of your Computer
3)Press any other key/digit to EXIT''')
command=int(input("Enter your choice here: "))
if command==1:
end=1 #i.e. below outer for loop will only run once in range(0,1) since only single Drive is to be checked
Drive=input("Enter Drive/Path: ")
if ':' not in Drive:
Drive+=':'
elif command==2:
end=24
else:
end=0 #i.e. below outer for loop will NOT run in range(0,0), i.e. Program will NO ACTION takes place.
for d in range(0,end):
if command==2:
Drive=chr(ord("A")+d)+":"
image_list=[]
video_list=[]
python_list=[]
image_count=video_count=python_count=0
for root,subdir,file in os.walk(Drive):
for f in file:
PATH=os.path.join(root,f)
if extension(PATH) in [".jpg",".jpeg",".png",".gif",".tiff",".psd",".eps",".ai"]:
image_count+=1
image_list.append(PATH)
elif extension(PATH) in [".yuv",".wmv",".webm",".vob",".viv",".svi",".roq",".rmvb",".rm",".nsv",".mxf",".mng",".mkv",".m4v",".gifv",".gif",".flv",".flv",".drc",".avi",".asf",".amv",".3gp",".3g2",".qt",".mov ",".f4b",".f4a",".f4v",".flv ",".mpeg",".mp2",".mp4 ",".ts",".m2ts",".mts ",".ogg",".ogv "]:
video_count+=1
video_list.append(PATH)
elif extension(PATH) in [".py"]:
python_count+=1
python_list.append(PATH)
if(image_count+video_count+python_count>0):
print("Drive: ",Drive,":")
print("IMAGE FILES:-\n",image_list,"\nImage Count=",image_count,"\n","-"*50)
print("VIDEO FILES:-\n",video_list,"\nVideo Count=",video_count,"\n","-"*50)
print("PYTHON FILES:-\n",python_list,"\nPython Count=",python_count,"\n","-"*50)
import os
ReplyDeleteos.path.exists
path=input(" enter the path\n")
isExist = os.path.exists(path)
print(isExist)
imgcount = 0
vidcount = 0
txtcount = 0
for path,subdir,files in os.walk(path):
#for file in subdir:
#print (os.path.join(path,name)) # will print path of directories
for file in files:
if file.endswith('.jpg') or file.endswith('.jpeg') or file.endswith('.png'):
imgcount = imgcount+1
elif file.endswith('.mkv') or file.endswith('.mp4'):
vidcount=vidcount+1
elif file.endswith('.txt' )or file.endswith('.docx') : # total File 1492
txtcount = txtcount+1
#print('Size: '+str(max_size)+' bytes')
print("Total images are "+str(imgcount))
print("Total video files are "+str(vidcount))
print("Total text are "+str(txtcount))
import os
ReplyDeleteos.path.exists
path=input(" enter the path\n")
isExist = os.path.exists(path)
print(isExist)
img = 0
vid = 0
txt = 0
for path,subdir,files in os.walk(path):
for file in subdir:
#print (os.path.join(path,name)) # will print path of directories
for file in files:
if file.endswith('.jpg') or file.endswith('.jpeg') or file.endswith('.png'):
img = img+1
elif file.endswith('.mkv') or file.endswith('.mp4'):
vid=vid+1
elif file.endswith('.txt' )or file.endswith('.docx') : # total File 1492
txt = txt+1
print("Total images are "+str(img))
print("Total video files are "+str(vid))
print("Total text are "+str(txt))
POST Answer of Questions and ASK to Doubt