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.
line = fh.read()
Size=len(line)
print(“Size of the file is ",Size ,”bytes”)
line = fh.readlines()
Count=len(line)
print(“Number of lines in the file is ",Count)
They are
(1) write() method
(2)writelines() method
FILE
WRITING METHODS
(1) write() method
This method writes a string to a file referenced by
its file-handle/file object. The file may be a non-
existing or an existing one.
Syntax: file-handle.write(string)
Example: F.write(line)
NOTE: For writing data onto a text file, first open the
file in write mode, ”w”. If the file is an existing one,
data will be overwritten else creates a non-existing or a
new file.
FILE
WRITING METHODS
#pyfiles6.py
# To create a new text file
Fout= open("New.txt","w")
N=int(input("No.of lines:"))
for I in range(N):
Line=input("Statement:")
Fout.write(Line)
Fout.close()
FILE
WRITING METHODS
#pyfiles7.py
# To create a new text file
Fout= open("New2.txt","w")
N=int(input("No.of lines:"))
for I in range(N):
Line=input("Statement:")
Fout.write(Line)
Fout.write('\n')
Fout.close()