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:

# open file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name 
 
This would produce following result:
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:

# open file
fo = open("aks.txt")
print "Name of the file: ", fo.name 

# Close opend file
fo.close()
# open file
fo=open("aks.txt",'w')
print (fo.name)

# Close opend file
fo.close()