Directory and File Mangement in Python
A directory or folder is a collection of files and sub directories. Python has the os module, which provides us with many useful methods to work with directories
mkdir() : it is used to create the directory
Syntax: os.mkdir("newdir")
chdir() method to change the current directory.
Syntax: os.chdir("newdir")
getcwd() method displays the current working directory
Syntax: os.getcwd()
rmdir() method deletes the directory
os.rmdir('dirname')
rename() change the direcotory name
os.rename(“oldname”,”newname”)
os.path.join() contains functions for manipulating filenames and directory names.
os.path.split() functions to split full pathnames, directory names, and filenames into their constituent parts.
glob.glob() the glob module is another tool in the Python standard library. It's an easy way to get the contents of a directory programmatically, and it uses the sort of wildcards that we may already be familiar with from working on the command line.
os.stat() function returns an object that contains several different types of metadata about the file
os.path.realpath() returns absolute path
Program on Directory Functions
import os
s=os.getcwd()
print("Working Directory ",s)
os.mkdir("dgp")
os.chdir("dgp")
print(os.getcwd())
os.chdir("d:/vision")
os.rename(“dgp.py”,”vision.py”)
os.rmdir("dgp")
print("Direcory Removed")
programe to print the directory and files
import os
s=os.getcwd()
print("Working Directory ",s)
for i in os.listdir():
print(i)
progam on os.path,glob fuctions
import os
import glob
print(os.path.join("/vision/","dgp"))
s="/vision/mypackage/area.py"
(dname,fname)=os.path.split(s)
print(dname)
print(fname)
#print(glob.glob("*.py"))
print("only python files")
for f in glob.glob("mypackage/*.py"):
print(f)
s=os.stat("math.py")
print(s)
print("real path")
p=os.path.realpath("math.py")
print(p)
For
Online Classes
Contact Us: 9885348743
Online Classes
Contact Us: 9885348743