You are on page 1of 18

File Handling

1
Prepared By:
Sudipta Baladhikary
Computer Science Department
Hariyana Vidya Mandir
6/24/2020
CLOSING A FILE:
• close() function is used to close a file

• Syntax: <file_objectname>.close( )

• Example:

csfile=open(“python.txt”)
csfile.close( )

6/24/2020 2
CLOSING A FILE:
• close() function breaks the link of file object/ file handle and the file on the disk.

• After close( ), no tasks can be performed on that file.

• open( ) is a built -in function used standalone whereas close( ) is a method used with file
handle object

6/24/2020 3
Reading from files

read( ) readline( ) readlines( )

6/24/2020 4
READ FUNCTIONS:
Method Syntax Description

read( ) <filehandle>.read([n]) Read at most n bytes from the file.


If no n is specified, reads whole file up to the end of the file
Return type is string.

readline( ) <filehandle>.readline(([n]) Read individual lines of a file; reads a file till the newline
including the newline character.
Return type is stirng.

readlines( ) <filehandle>.readlines() Read all lines and returns them in a list

6/24/2020 5
EXAMPLE 1:

Text file

Python code to
read n bytes from
the above file
6/24/2020 6
OUTPUT:

Read 45 bytes from the file

6/24/2020 7
EXAMPLE 2:

Text file

Python code to
read whole file

6/24/2020 8
OUTPUT:

Read whole file

6/24/2020 9
EXAMPLE 3:

Text file

Python code to
read a line

6/24/2020 10
OUTPUT:

Read one line from a file

6/24/2020 11
EXAMPLE 4:

Text file

Python code to
read whole file
line by line using
loop

6/24/2020 12
OUTPUT:

Read whole file

6/24/2020 13
EXAMPLE 5:

Text file

Python code to read the file


line by line using for loop

6/24/2020 14
OUTPUT:

Read only three lines from file

REASON:
for a in csfile: is already iterating over the lines in the file, you are then attempting to
read a line within that iteration .

6/24/2020 15
EXAMPLE 6:

Text file

Python code to read whole


file using readlilnes()

6/24/2020 16
OUTPUT:

Read whole file and return as


list

6/24/2020 17
18

6/24/2020

You might also like