Python os module- File operations in Python using python os module

Python provides os module which can be used to perform File operations like - create, read, write and delete. Below program performs following operation -
1. Check for a directory and create if it does not exist
2. Create a file .
3. Write into file
4. Rename file
5. Delete files
6. Delete Directory

Sample program to illustrate various file operation using os module of python :- 


import os
import sys
import tempfile
def dofileoperation():
    dirExist=0
    tempdir=tempfile.gettempdir()
    if os.path.isdir(tempdir):
        print "temp directory exist!!"
        dirExist=1
    else:
        print "No temp directory exists, \
            so create user defined directory"
        dir="C:\tempPython"
        create_temp_dir(dir)
        dirExist=1
    if dirExist==1:
        os.chdir(tempdir)
        current_working_dir = os.getcwd()
        print "Current working directory is " + current_working_dir
        print "Create 'example' directory if does not exist"
        if os.path.isdir('example'):
            pass
        else:
            create_dir('example')

        #change directory to example
        os.chdir('example')
        current_working_dir=os.getcwd()
        print "\nNew working directory is " + current_working_dir

        print "Creating three file in current working directory "
        for i in range(1,3):
            file_handle=create_file_writemode('input'+str(i))
            write_into_file(file_handle,'Hello file\nI \
                am first line\nI am second line')

        print "\nCurent directory listing are " 
        current_dir_listing(current_working_dir)

        print "\nDisplay fully qualified of all \
            file in current directory"
        full_qualified_name(current_working_dir)
        
        first_file= os.path.join(current_working_dir,\
            os.listdir(current_working_dir)[0])
        print "\nDisplaying file contents of file: " + first_file
        read_file_content(first_file)

        print "Rename first file in current directory "
        file_rename(first_file,first_file+'_new')
        print "\nCurent directory listing after file rename " 
        current_dir_listing(current_working_dir)

        print "\nDeleting all files in current directory"
        delete_files_indir(current_working_dir)
        
        print "\nCurent directory listing are " 
        current_dir_listing(current_working_dir)

        print "\nDeleting working directory 'example' "
        delete_dir('example')

        print "\nChecking existance of example dir" 
        if os.path.isdir('example'):
            print 'example directory exists!!'
        else:
            print 'example directory deleted successfully !!'
def create_dir(dir):
    os.mkdir(dir)

def delete_dir(dir):
    #print os.pardir
    os.chdir(os.pardir)
    #print os.getcwd()
    os.rmdir(dir)

def create_file_writemode(filename):
    return open(filename,'w')

def get_filehandle(filename):
    return open(filename)

def write_into_file(file_handle,text):
    file_handle.write(text)
    file_handle.close()

def full_qualified_name(current_working_dir):
    for filename in os.listdir(current_working_dir):
            print os.path.join(current_working_dir,filename)

def current_dir_listing(current_working_dir):
    print os.listdir(current_working_dir)

def read_file_content(filename):
    file_handle = open(filename)
    allLines = file_handle.readlines()
    for eachline in allLines:
        print eachline

def delete_files_indir(current_working_dir):
    for filename in os.listdir(current_working_dir):
        os.remove(os.path.join(current_working_dir,filename))

def file_rename(oldname,newname):
    os.rename(oldname,newname)

if __name__ == '__main__':
    dofileoperation()

Sample output
:-

C:\Python27\sample->python fileop.py
temp directory exist!!
Current working directory is c:\users\nranjan\appdata\local\temp
Create 'example' directory if does not exist

New working directory is c:\users\nranjan\appdata\local\temp\example
Creating three file in current working directory

Curent directory listing are
['input1', 'input2']

Display fully qualified of all             file in current directory
c:\users\nranjan\appdata\local\temp\example\input1
c:\users\nranjan\appdata\local\temp\example\input2

Displaying file contents of file: c:\users\nranjan\appdata\local\temp\example\input1
Hello file

I                 am first line

I am second line
Rename first file in current directory

Curent directory listing after file rename
['input1_new', 'input2']

Deleting all files in current directory

Curent directory listing are
[]

Deleting working directory 'example'

Checking existance of example dir
example directory deleted successfully !!

4 Comments

Previous Post Next Post