FILE OPENING AND CLOSING
FILE OPENING AND CLOSING
Here passed parameter is a number of bytes to be read from the opened file.
For Example if the file have the content,
sample.txt – Problem Solving and Python Programming.
Example Program
Output
Read string is : Problem So
Read string is : lving and Python Pro
Read string is : gramming
2. write() Method
This method writes a string from an open file.
Syntax:
file_object.write(“String”)
Example:
f=open("F:/Python/test.txt","w+")
print(f.write(“This is my first file”))
print(f.read())
f.close()
Output:
This is my first file
There are two functions to read a file line by line, then there are two methods
readline()
readlines()
1.readline()
Every time a user runs the method, it will return a string of characters that
contains a single line of information from the file.
Syntax: file_object.readline()
Example
Consider the file test.txt contain these three lines
This is the First Line in the file
This is the Second Line in the file
This is the Third Line in the file
Now the Python source code is
f=open("F:/Python/test.txt","r")
print(f.readline())
f.close()
Output:
This is the First Line in the file
2. readlines() method
This method is used to return a list containing all the lines separated by the special character (
\n ).
Syntax:
file_object.readlines()
Example
Consider the same file
Now the Python source code is
f=open("F:/Python/test.txt","r")
print(f.readlines())
f.close()
Output
['This is the First Line in the file\n', 'This is the Second Line in the file\n', 'This is the Third
Line in the file']
f=open("test.txt","r")
for line in f:
print(line)
f.close()
Output:
This is the First Line in the file
This is the Second Line in the file
This is the Third Line in the file
Example: