Friday, January 20, 2012

Python Note 5 (File Handling)

File handling is very easy in python, Lets see an example
datafile=open("myfile.dat","w") #open a file for writing
datafile.write("Sri Lanka,India,Pakistan,Bhutan,Australlia,Canada") #write data
datafile.write("\n")
datafile.write("Apple,Orange,Mango")
datafile.close() #release the file

#reading from the file
datafile=open("myfile.dat","r") #open file for reading
record=datafile.readline()#reding a line (here it is the first line)
mylist=record.strip("\n").split(",") #remove newline character and split the string by comma
print(mylist)
print(len(mylist))



  • Dicts and Files
dict={}
dict['J']="Java"
dict['C']="C++,C"
dict['P']="Prolog"
dict['V']="VB"
print (dict)
print (dict['J'])
print ('J' in dict)
if 'J' in dict :
 print ("J for : " + dict['J']) #throws if key is not available
else :
 print ("Invalid key")
print(dict.get('V')) #don't throws KeyError instrad returns None
Looping a dictionary

  ## By default, iterating over a dict iterates over its keys.
  ## Note that the keys are in a random order.
  for key in dict: print key
  ## prints a g o
  
  ## Exactly the same as above
  for key in dict.keys(): print key

  ## Get the .keys() list:
  print dict.keys()  ## ['a', 'o', 'g']

  ## Likewise, there's a .values() list of values
  print dict.values()  ## ['alpha', 'omega', 'gamma']

  ## Common case -- loop over the keys in sorted order,
  ## accessing each key/value
  for key in sorted(dict.keys()):
    print key, dict[key]
  
  ## .items() is the dict expressed as (key, value) tuples
  print dict.items()  ##  [('a', 'alpha'), ('o', 'omega'), ('g', 'gamma')]

  ## This loop syntax accesses the whole dict by looping
  ## over the .items() tuple list, accessing one (key, value)
  ## pair on each iteration.
  for k, v in dict.items(): print k, '>', v
  ## a > alpha    o > omega     g > gamma
Ref : http://code.google.com/edu/languages/google-python-class/dict-files.html

Formatting Dictionary values
myhash={}
myhash['fruit']="Apple"
myhash['amount']=2
myhash['price']=25.75
strng=" Unit : %(fruit)s \n Amount : %(amount)d \n Price : %(price)0.4f " %myhash
print(strng)

del : del operator can delete an definition of a variable
  var = 6
  del var  # var no more!
  
  list = ['a', 'b', 'c', 'd']
  del list[0]     ## Delete first element
  del list[-2:]   ## Delete last two elements
  print list      ## ['b']

  dict = {'a':1, 'b':2, 'c':3}
  del dict['b']   ## Delete 'b' entry
  print dict      ## {'a':1, 'c':3}
Ref : http://code.google.com/edu/languages/google-python-class/dict-files.html

  • File Operations
open('name',mode) method returns a file handle. we can read, write to the file using file handle.
there are different different modes
  • 'r' - reading
  • 'rU' - U means universal way
  • 'w' - write
  • 'a' - append
hndl=open('myfile.dat','r')
for line in hndl :
 print (line)
hndl.close()

  • Reading Unicode files 
we can use codec module to read Unicode files
import codecs

hndl=codecs.open('unicodefile.dat','rU','utf-8')
for line in hndl :
 print (line) #print is not supported with unicode strings
hndl.close()
  • Reading a text file entirely
hndl=open("txtfile.txt","r")
text=hndl.readlines()
print(text)
print(text[2]) ##prints 3rd line
hndl.close()

0 comments:

Post a Comment

© kani.stack.notez 2012 | Blogger Template by Enny Law - Ngetik Dot Com - Nulis