Professional Documents
Culture Documents
Closing a File:
It is done using the close() method of its file-object/ file
handle.
It breaks the link of the file-object/ file handle and
the file on the disk.
It is very important that an opened file has to be closed
at the end of its use in the program.
In Python, files are automatically closed at the end of the
program but it is a good practice to close the files
explicitly.
If the read hits EOF before obtaining size bytes, then it reads only
available bytes.
Syntax: fileObject.read([n])
FILE
READING METHODS
The read() Method
Syntax: fileObject.read([n])
Examples:
(1) line = fh.read(10)
(2) line=fh.read()
FILE
READING METHODS
# pyfiles1.py
fh = open("c:\\temp\\data.txt", "r")
print("Name of the file: ", fh.name)
# The text file has following 4 lines
#A specimen for a text file is in a different folder.
#The name of the folder is Temp.
#The drive is C:
#And the path of the file is C:\temp\data.txt
line = fh.read(10)
print("Read Line:",line)
Syntax: fileObject.readline([n])
Examples:
(1) line = fh.readline(10)
(2) line=fh.readline()
FILE
READING METHODS
# pyfiles2.py
fh = open("c:\\temp\\data.txt", "r")
print("Name of the file: ", fh.name)
# The text file has following 4 lines
#A specimen for a text file is in a different folder.
#The name of the folder is Temp.
#The drive is C:
#And the path of the file is C:\temp\data.txt
line = fh.readline(10)
print("Read Line:",line)
This method starts reading from the beginning of the file till the
end and returns them as a list.
Example:
line = fh.readlines()
FILE
READING METHODS
# pyfiles3.py
fh = open("c:\\temp\\data.txt", "r")
print("Name of the file: ", fh.name)
# The text file has following 4 lines
#A specimen for a text file is in a different folder.
#The name of the folder is Temp.
#The drive is C:
#And the path of the file is C:\temp\data.txt
line = fh.readlines()
print("Read Line:",line)
They are
(1) read() method