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 !!

7 Comments

  1. As usual, great post. You keep amazing me with your content design and layout


    토토사이트
    토토365프로
    프로토

    ReplyDelete
  2. That is a very good tip particularly to those fresh to the blogosphere.
    Short but very accurate information…



    스포츠토토
    배트맨토토프로
    배트맨토토

    ReplyDelete
  3. Well written. Keep sharing like this informative blogs. Python training in Delhi is the also right place where students can learn ore file operation in python.

    ReplyDelete

  4. When looking to personalize your apparel, exploring different transfer options can make a significant difference. One popular choice is the custom dtf transfer, which offers high-quality and vibrant results. This method allows for detailed and durable designs that stand out on any fabric. Whether for small orders or large batches, these transfers provide a reliable solution for custom printing needs.

    ReplyDelete
Previous Post Next Post