Python file operations – read/write/append

 

To read and existing file use following code. In this code I am trying to read inputFile, it will throw IOError if given input file is not available.

import os, sys
#Opening file in read mode
f = open("inputFile", 'r')
#Reading all lines in input text as list
lines = f.readlines() 
print lines
for line in lines:
    #Printing each line in list
    print line 
f.close()

To write output to a file use following code. In this code I am opening file with write mode using ‘w’. In write mode it will create input file if it dos not exists and write content to it or if input file exists it will overwrite content of input file with new text.

import os, sys
#Opening file in write mode
f = open("inputFile", 'w') 
#Writing hello to input file
f.write("hello") 
f.close()

To append output to existing file use we need to open file with append mode using ‘a’. In following code I am opening file with append mode. In append mode it append content to input file if it exists else it will create input file and append content to it.

import os, sys
#Opening file in append mode
f = open("inputFile", 'a') 
#Appending hello to input file.
f.write("hello") 
f.close()
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s