Showing posts with label file I/O in python. Show all posts
Showing posts with label file I/O in python. Show all posts

Wednesday, July 29, 2015

Python Tkinter Programming

Desktop GUI application creation in an easy mode is one of the specialty of the python programming. Python 2.7 and Python 3 both have an inbuilt class tkinter which is needed to program graphical interface in python. There are other modules as well but here we will focus only on tkinter.

A basic tkinter program to show 'Hello World' in GUI mode -

from Tkinter import *
# create a root window
root = Tk()
root.title("Lazy Buttons")
root.geometry("400x120")
lbl=Label(root,text="Hello World").pack()

root.mainloop()

If this shows error, change the Tkinter to tkinter in the import statement. After importing the module we create the root window by defining is as the Tk() object. In the next statement we named the window as "Lazy Buttons" by calling the root.title() method.
root.geometry() is used to define the width and height of the window. It has a formal notation like root.geometry("w x h+ x+ y") where w and h are for width and height respectively and the x and y are the coordinates of the screen.

In the next statement we created a Label, which will show the "Hello World" texts to be displayed  in the root window. The Label creator method takes the window name as input i.e. root and the text as input.The pack() method is needed to pack the label to the root window. The mainloop is needed to make the window to exist forever until you click the cross button.
Buy One Plus Two without Registration

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.

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