The open Function:

Before you can read or write a file, you have to open it using Python’s built-in open() function.


Syntax

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


1. file_name:Name of file

2. access_mode: The access_mode determines the mode in which the file has to be opened ie. read, write append etc.
to see all access mode click here

3. buffering:Table shown below


buffering value meaning
0
no buffering will take place
1
line buffering will be performed while accessing a file
> 1
then buffering action will be performed with the indicated buffer size
< 0
the buffer size is the system default

EXAMPLE:

  1. # open file
  2. fo = open("foo.txt", "wb")
  3. print "Name of the file: ", fo.name

This would produce following result:

  1. Name of the file: foo.txt


The close Function:

Close() method closes the file object 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:

  1. # open file
  2. fo = open("aks.txt")
  3. print "Name of the file: ", fo.name
  4.  
  5. # Close opend file
  6. fo.close()
  1. # open file
  2. fo=open("aks.txt",'w')
  3. print (fo.name)
  4.  
  5. # Close opend file
  6. fo.close()