Table of Contents
show
File Read
To read data from a file, open the file in read mode. Methods to read data from a text file
Read
The read( ) method is used to read a string from an already opened file. The string can include alphabets, numbers, characters or other symbols
Syntax
read( )
Fileobj.read(count)
- Count is an optional parameter, which if passed to the read( ) method specifies the number of bytes to read from the opened file.
- The read( ) method starts reading from the beginning of the file and if count is missing or has a negative value, then it reads the entire the content of the file(i.e., till the end of file)
Example
Python is easy
problem solving
python programming
GE8151
GE8161
file1 = open("myfile1.txt", "r")
print(file1.read(7))
file1.close()
Output
Python
readline
The readline( ) method is used to read a single line from the file. The method returns an empty string when the end of the file has been reached.
Syntax
readline( )
Fileobj.readline( )
Example
file1 = open("myfile1.txt", "r")
print(file1.readline())
print(file1.readline())
file1.close()
Output
Python is easy
problem solving
readlines
The readlines( ) method is used to read all the lines in the file.
Syntax
readlines( )
Example
file1 = open("myfile1.txt", "r")
print(file1.readlines())
file1.close()
Output
['Python is easy \n', 'problem solving \n', 'python programming\n', 'GE8151\n', 'GE8161']
Views: 0