Skip to main content

Files IO & Pickles

How to make this FILE process in Python? 

The Standard Input, Standard Output are the two fileobjects genrally accessible from the operating system provided interfaces which allows us to change files.

How to redirect this output... normally output is coming from print command in the Python. Can you send the data/text to a file? Yes we can using file object.
File IO Process in Python

The file open modes

Python file open modes are same as C language by default it will be open in read mode. The open() method returns a file object or file pointing reference. 
Syntax: 
fileobject = open(file_name [, access_mode][, buffering]) 
where basic file operational mode can be 'r' (read), 'w'(write) or 'a'(append). 
The default mode is 'r' that is read mode and the file can be ANSI Text file or binary file (b). They can be opened in combined mode ‘rb+’ 
That every file that you opened in the code must be closed. The close() method closes an opened file object or you can dereferences.
Syntax: fileObject.close()

File Advanced open modes

File Advanced opening modes in Python

The file attributes

Following table have the list of the file object attributes. Which we can directly access them public.

AttributeDescription
file.closedReturns true if file is closed, false otherwise.
file.modeReturns access mode with which file was opened.
file.nameReturns name of the file.
# This program illustrates the file attributes

f=open('fileattr.py')
print "mode:",f.mode
print "name:",f.name

if f.closed:
        print f.name, " is closed"
else:
        print f.name," is not closed"

Its execution gives the output as follows
>>> execfile('fileattr.py')
mode: r
name: fileattr.py 
fileattr.py is not closed

We started experimenting with Files and Pickle soon we will update you on that... Object oriented pickling !!!

  1. Create your own object
  2.  Push the object into pickle
  3.  Dump, load functions explore
  4.  persistance of objects
  5.  Reusing the object after a restart of Python Shell

Pickle for Patient object persistance

import pickle
"""
This program is to illustrate the Pickle module usage in Python
"""

class Patient:
 def __init__(self, n, a):
  self.name=n; self.age=a
 
 def __repr__(self):
  return self
 
 def Printpatient(self):
  print self.name, self.age

if __name__=="__main__":
 """ This is main program for Patient database program """
 
 p=[] # This list is to dump
 x=[]  # This list is for load from pickle
 
 for i in range(0,2):
  n=raw_input('Enter name of the Patient:' )
  a=input('Enter age of the patiet: ')
  p.append(Patient(n,a))
 #Storing the list of Patient objects into a file
 fp=open('Patient.txt','wb') # Write in bin format
 pickle.dump(p,fp)
 fp.close()
  
 fp=open('Patient.txt','r+')
 x=pickle.load(fp)
 for i in x:
  i.Printpatient()

>>> execfile('c:/pybin/PatientFile.py')
Enter name of the Patient:Nageshwarrao
Enter age of the patiet: 89
Enter name of the Patient:Sridhar
Enter age of the patiet: 51
Nageshwarrao 89
Sridhar 51

Comments

Popular posts from this blog

Python Interview Questions -Coding Snipets

 This post is dedicated for all DevOps Engineer, Software Engineers who are preparing for Coding Interviews,  Overview of Coding Interviews Most Companies looking for People with minimum Coding knowledge. In a coding interview, you will be given a small problem to solve within 10 - 20 minutes online screen or in-person on their system. In the question, you might be having some part of the code framed and you might be asked to write a snippet of code in between. You need to understand the code comments and proceed to build the expected snippet of code. Bigger companies look for the General purpose questions, where small companies look for specific questions. The General questions would be like this: Determine if the given word is a palindrome or not. (Example madam) Determine given number is prime or not. How to prepare for a coding interview? Now we have the flexibility to choose the programming language on which you are comfortable.  In general DevOps Infra guys will be ...

Python Sets and Dictionaries

Python Sets Python Maps examples A mapping object maps hashable values to arbitrary objects. Mappings are mutable objects. There is currently only one standard mapping type, the dictionary. Dictionaries consist of pairs (called items) of keys and their corresponding values. Dictionaries can be created by placing a comma-separated list of key: value pairs within curly braces Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples. Python Set Operations and methods Python Set methods continueed >>> SET={'new','old','list','new'} >>> SET set(['new', 'old', 'list']) Lets play with set operations, it is more like school math here... >>> s={1,2,3,4} >>> k={3,4,5,6} >>> len(s) 4 >>> len(k) 4 >>> 1 in s True >>...

Program Controls and loops in Python

Python Programming controls The flow of program will be controlled with conditional statements where this flow  if condition if-else condition if-elif condition while loop while - else loop for loop for with if- else loop if condition Here I would like to work on program control statements, wherein relate some operating system functionalities so that, this would give some basic prototype for the sys admin scripts. #!/usr/bin/python # This illustrate if condition # Filename : ifex.py import os d=os.listdir('/home/pavanbsd/pybin') print d f='ifex.py' if f in d: print "File exists" else: print "Not found..." if-elif-else ladder No worries, coming soon... When you need the task that need to be done repeatedly then your choice is using loops. Python provides two simple loop constructs easy to use! More powerful then other scripting compare to, it has 'else' block. while loop Understand the power of while loop,...