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

5 Comments

  1. I am glad that I saw this post. It is informative blog for us and we need this type of blog thanks for share this blog, Keep posting such instructional blogs and I am looking forward for your future posts.
    Python Projects for Students

    Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills, including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing, promoting and account.

    Project Center in Chennai

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


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

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



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

    ReplyDelete
  4. 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
Previous Post Next Post