Python OS Module



import os
#When working with os module makesure you are not running code that will create or delete something new everytime e.g mkdir()
#Change to another directory
os.chdir("/storage/emulated/0/")
#Get current working directory
print(os.getcwd())
#List files and folders in directory
print(os.listdir(#can take directory as input, default is current directory
))
#Making directories
#os.mkdir("Testing")
#print(os.listdir())
#os.makedirs("Reaching/Inside/Richard")
#What above code does is to create directories after slashes nested from top to bottom
print(os.listdir())
#You will see if you change your directory to "Reaching" you will find "Inside" there then inside that you will find "Richard", that is how makedirs() work

#let us talk about a bad practice python programmers do will concatenating directories and file together, you dont have to do that there is a method that does that better that you do, os.path..
dir1="/fake/dirt"
dir2="fat.jpg"
dirfull=os.path.join(dir1,dir2)
print(dirfull)
#print(dir(os.path))
a=os.path.dirname(dirfull)#returns directory
b=os.path.basename(dirfull)#return basename
print(a)
print(b)
print(os.path.split(dirfull))#splits basename and dirname in a tuple
print(os.path.splitext(dirfull))#splits extention of basename file and basename with dirname
print(os.path.exists(dirfull))#returns true if the path exists
print(os.path.isdir(dirfull))#returns true is a path is a dir
file1=os.stat("unique.py")#returns a tuple of properties of a file e.g the modification time then we can get it
from datetime import datetime
time1=datetime.fromtimestamp(file1.st_mtime)
print(time1)#This is the best way to get the time in a human readable format, i will be uploading a tutorial on datetime module too, you can get the file size with os.stat too play with it to understand more

#Magical os.walk() recursive filer
#os.walk() walks through all the directories and return a tulpe of length 3 of current dir path, directory folders, dir files
"""for dirPath, dirFolders, dirFiles in os.walk(os.getcwd()):
print(dirPath)
print(dirFolders)
print(dirFiles)
print()
"""
#Let us solve a simple problem, imagine you phone memory is full, but you dont know where the big files are, i will write a program to get those for us
for dirPath, dirFolders, dirFiles in os.walk(os.getcwd()):
for i in dirFiles:
path1=os.path.join(dirPath,i)
size=os.stat(path1).st_size#in bytes
#converting to mb
size=(size/1024)/1024
if size > 100:
#50mb
print(i)
os.rmdir(path1)
#So thank you for reading my articl, please share to others i think the example is great, try to create a program that will search all mp3 files on your memory card

Post a Comment

0 Comments