Industrial Training

Opening And Closing File


File handling is an important part of any web application.


Python has several functions for creating, reading, updating, and deleting files.


File Handling


The key function for working with files in Python is the open() function.


The open() function takes two parameters; filename, and mode.


There are four different methods (modes) for opening a file:


"r" - Read - Default value. Opens a file for reading, error if the file does not exist

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

"x" - Create - Creates the specified file, returns an error if the file exists

In addition you can specify if the file should be handled as binary or text mode


"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)

Syntax


To open a file for reading it is enough to specify the name of the file:


f = open("demofile.txt")

The code above is the same as:


f = open("demofile.txt", "rt")

Because "r" for read, and "t" for text are the default values, you do not need to specify them.


Printing to the Screen


The simplest way to produce output is using the print statement where you can pass zero or more expressions separated by commas. This function converts the expressions you pass into a string and writes the result to standard output as follows −


#!/usr/bin/python

print "Python is really a great language,", "isn't it?"

This produces the following result on your standard screen −


Python is really a great language, isn't it?

Reading Keyboard Input


Python provides two built-in functions to read a line of text from standard input, which by default comes from the keyboard. These functions are −


  • raw_input
  • input

The raw_input Function


The raw_input([prompt]) function reads one line from standard input and returns it as a string (removing the trailing newline).


#!/usr/bin/python

str = raw_input("Enter your input: ")
print "Received input is : ", str

This prompts you to enter any string and it would display same string on the screen. When I typed "Hello Python!", its output is like this −


Enter your input: Hello Python
Received input is :  Hello Python

The input Function


The input([prompt]) function is equivalent to raw_input, except that it assumes the input is a valid Python expression and returns the evaluated result to you.


#!/usr/bin/python

str = input("Enter your input: ")
print "Received input is : ", str

This would produce the following result against the entered input −


Enter your input: [x*5 for x in range(2,10,2)]
Recieved input is :  [10, 20, 30, 40]

Opening and Closing Files

Until now, you have been reading and writing to the standard input and output. Now, we will see how to use actual data files.


Python provides basic functions and methods necessary to manipulate files by default. You can do most of the file manipulation using a file object.


The open Function


Before you can read or write a file, you have to open it using Python's built-in open() function. This function creates a file object, which would be utilized to call other support methods associated with it.


Syntax


file object = open(file_name [, access_mode][, buffering])

Here are parameter details −


  • file_name − The file_name argument is a string value that contains the name of the file that you want to access.
  • access_mode − The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. A complete list of possible values is given below in the table. This is optional parameter and the default file access mode is read (r).
  • buffering − If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is performed while accessing a file. If you specify the buffering value as an integer greater than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size is the system default(default behavior).

The close() Method


The close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done.


Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.


Syntax


fileObject.close()

Example


#!/usr/bin/python

# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name

# Close opend file
fo.close()

This produces the following result −


Name of the file:  foo.txt
Hi I am Pluto.