Professional Documents
Culture Documents
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.
• 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
6/24/2020 4
READ FUNCTIONS:
Method Syntax Description
readline( ) <filehandle>.readline(([n]) Read individual lines of a file; reads a file till the newline
including the newline character.
Return type is stirng.
6/24/2020 5
EXAMPLE 1:
Text file
Python code to
read n bytes from
the above file
6/24/2020 6
OUTPUT:
6/24/2020 7
EXAMPLE 2:
Text file
Python code to
read whole file
6/24/2020 8
OUTPUT:
6/24/2020 9
EXAMPLE 3:
Text file
Python code to
read a line
6/24/2020 10
OUTPUT:
6/24/2020 11
EXAMPLE 4:
Text file
Python code to
read whole file
line by line using
loop
6/24/2020 12
OUTPUT:
6/24/2020 13
EXAMPLE 5:
Text file
6/24/2020 14
OUTPUT:
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
6/24/2020 16
OUTPUT:
6/24/2020 17
18
6/24/2020