Saturday, July 18, 2015

Python File I/O

Python comes with easy to use inbuilt functions for handling files. Like other programming practices files can be opened in read , write and append mode in python. There are also binary read and write mode and also r+ mode available. I will go through each of them.

To open a file , you have to write -
   f=open('filename','mode')
The default mode  in python is 'r' mode i.e. if you don't supply anything to mode option it will open the file in read mode. In read mode you can only read the file, you can not modify or erase the file content.
In write mode you can create a file. It erases a file if it has a same name. So handle it carefully, you don't want to delete important file with same name.
Append mode helps to write something in an already written file. It appends the new data in the file without deleting previous content.
In r+ mode you can open the file in both read and write mode altogether.

Let's understand a file operation by example.

This python program examples will find out share price of your favorite share and make a file consisting of all the share prices in different interval of times.

import urllib,time
f=open('mcxwholedayprice.txt','w')
s=str(time.strftime("%H:%M:%S"))
(hour,minutes,seconds)=s.split(':')
hour=int(hour)
curhour=0
while curhour<hour+12:
      
        page=urllib.urlopen("https://www.google.com/finance?q=NSE%3AMCX&ei=eIqoVcGIEsuYuATZpZ3gBw")
        text=page.read().decode("utf8")
        #print text
        text=text.lstrip()
        where=text.find("ref_272295776418103_l")
        #print where
        a="The MCX Share Price ",text[where+23:where+31]
        f.write(str(a))
        time.sleep(900)
        s=str(time.strftime("%H:%M:%S"))
        (curhour,minutes,seconds)=s.split(':')
        curhour=int(curhour)
f.close() 


Take a close look at the program above. The program imports two modules urllib and time. urllib is needed to open a website page from given url. First of all I needed to find the share price of my favorite share in google finance and write the link in the urlopen() function.Then I call time.strftime() to get the time now in a desired format and get the hour out of the format by s.split()-previously discussed in string section.
The while loop will run for 12 hours and record all the data needed to the variable a. The variable then converted to string and then written to the file we have opened in write mode. Finally it closes the file.
You can do it in your way, there are redundant line for better understanding and they can be easily removed. Can you find them out?

The other operation is read () method in python file handling. You have written a file in the previous program. To read the content of the file you need to write the following  -

f=open('mcxwholedayprice.txt','r')
print f.read()
f.close()

You can give arguments in read() function too.e.g. f.read(20) - Reads the twenty characters of the file.
f.readline() - Used to read single line of the file.
f.readlines() - Read the file line by line formatted as a list.
f.tell() - Tell the current position of file head or handler.
f.seek(n) - Goes direct to nth character of the file.



Visit my website for more free contents and more programs on files at http://pythonbeginner.in
and learn python.

No comments:

Post a Comment

Feautured Post

Python Trivia Post: enumerate()

Python has a very useful inbuilt function, which is called enumerate(). This is needed whenever you need the numbering of a certain element...