Reading data from a text file in python 3 | read(), readline(), readlines() in Python 3

Reading data from a text file in python | read(), readline(), readlines() in Python 3

Different predefined functions of Python to read data from file are::

1. read() method in Python

This function is used to read entire content of file or specific number of characters from file.

Syntax 1:

<file_object>.read()

Here file_object is the name of file handler object that is linked to a data file.

Example:

#Python Program to display entire content of text file data.txt

file1 = open(“data.txt”) #data.txt contains: I am a student
s=file1.read()
print(s)

Output

I am a student

** Above code will display contents of data file data,txt

Syntax 2:

<file_object>.read(N)

Here file_object is the name of file handler object that is linked to a data file.

N specified number of characters to be read from file.

Example:

file1 = open(“data.txt”) #data.txt contains: I am a student
s=file1.read(6)
print(s)

Output

I am a

** Above code will display first six characters (including spaces) from data file data.txt

 

2. readline() method in Python

This function is used to read single line at a time from an existing data file.

Syntax:

<file_object>.readline()

Here file_object is the name of file handler object that is linked to a data file.

Example 1:

#Python Program to display first line from text file data1.txt

Data file data1.txt contains following data:

This is a data file
It contains data about a student
Name of student is Amit

file1 = open(“data1.txt”) 
s=file1.readline()
print(s)

Output

This is a data file

** Above code will display first line from data file data1.txt

Example 2:

#Python Program to display data from text data1.txt line wise.

f=open("data1.txt","r")
s=" "
while s:
     s=f.readline()
     print(s)
f.close()

Output

This is a data file
It contains data about a student
Name of student is Amit

** Above code will display complete data from file one line at a time from file data1.txt

3. readlines() method in Python

This function is used to read entire content from data file and store it in the form of a list. Each line of data file would be stored as list element.

Syntax:

<file_object>.readlines()

Here file_object is the name of file handler object that is linked to a data file.

Example:

Data file data1.txt contains following data:

This is a data file
It contains data about a student
Name of student is Amit

Example 1: 

Program to demonstrate the use of readlines() method in  Python.

file1 = open(“data1.txt”) 
s=file1.readlines()
print(s)

Output

['This is a data file\n','It contains data about a student\n','Name of student is Amit\n']

** Above code will display data from data file data1.txt in the form of a list.

Example 2:

Python program to display the number of lines in a text file by using readlines() method in Python.

file1 = open(“data1.txt”) 
s=file1.readlines() 
count =len (s)
print (“Number of lines=”, count)
file1.close( )

Output

Number of lines=3

** Above code will display number of lines in data file data1.txt .

flush ( ) method in Python

When we write data into a file , Python keeps everything temporarily in buffer and saves it to actual file when close() function is called.

By using flush( ) function we can force Python to write the contents of buffer to the actual file on storage .

The syntax to use flush( ) function is :

<fileObject>. flush ( )

#Python program to demonstrate the use flush() method in Python

f = open ('newfile.txt', 'w+')
f.write ('Line 1')
f.flush( )
f.write ('Line 2')
f.flush( )
f.close( )

Other Programs

1. Python Program to read roll number and name of a students and store these details in a data file called “Marks.txt”.

Fileout = open ("Marks.txt", "a")
rollno= int (input("Enter Rollno="))
name= input ("Enter Name=")
record =str (rollno)+ "," + name + "\n"
Fileout.write(record)
Fileout.close( )

Output

Enter Rollno=101
Enter Name=aman

** Above code will read values of variables rollno and name and save it into data file Marks.txt in comma separated format. File has been opened in append mode i.e new records will be saved in the file at the end of existing file .

2. Python Program to display data saved in data file “Marks.txt” one line at a time.

Fileinput = open ("Marks.txt", "r")
s=" "  #Blank space stored in string variable s.
while s :
     s = Fileinput.readline( ) #Read one line at a time
     print(s)
Fileinput.close ( )

Output

101,aman

3. Python Program to display data saved in data file data1.txt one word at a time.

Fileinput = open ("data1.txt", "r")
s=" "
while s :
     s = Fileinput.readline( ) #Read a line from file
     words=s.split() #break line into a list or words
     for w in words: #Read one word at a time from list 
          print(w)
Fileinput.close ( )

Output

This
is
a
data
file
It
contains
data
about
a
student
Name
of
student
is
Amit

4. Python Program to count number of words in text file  data1.txt  

Fileinput = open ("data1.txt", "r")
s=" "
count=0
while s :
     s = Fileinput.readline( ) #Read a line from file
     words=s.split() #break line into a list or words
     for w in words: #Read one word at a time from list 
          count+=1 
print("Number of words=",count)
Fileinput.close ()

Output

Number of words= 16

5. Python Program to count number of characters in data file  data1.txt 

Fileinput = open ("data1.txt", "r")
s=" "
count=0
while s :
     s = Fileinput.read(1) #Read one character at a time.
     count+=1
print("Number of characters=",count)
Fileinput.close ()

Output

Number of characters= 78

6. Python Program to count number of vowels and consonants in data file data1.txt

Fileinput = open ("data1.txt", "r")
s=" "
count=0
count1=0
while s :
     s = Fileinput.read(1) #Read one character at a time.
     if s in ['a','e','i','o','u']:
          count+=1
     else:
          count1+=1
print("Number of vowels=",count)
print("Number of consonants=",count1)
Fileinput.close ()

Output

Number of vowels= 25
Number of consonants= 53

7. Python Program to add details of two students’ to the data file Marks.txt

Fileout = open (“Marks.txt”, “a”)
for i in range (2) :
     print (“Enter details for student”, (i+1), “below :”)
     rollno = int(input(“Enter rollno=”))
     name= input (“Enter Name=”)
     marks=float (input(“Enter Marks=”))
     rec =str(rollno)+”,”+ name +”,”+ str(marks)+’\n’
     Fileout.write(rec)
Fileout.close( )

Output

>>>
Enter details for student 1 below :
Enter rollno :17
Name : Amit
Marks : 74.6
Enter details for student 2 below :
Rollno : 18
Name : John
Marks : 99.2

8. Python Program to read and display details of students’ stored in data file Marks.txt .

Fileinp = open (“Marks.txt”, “r”)
while str :
     str = fileinp.readline( )
     print(str)
Fileinp.close ( )

Output

>>>

17,Amit , 74.6
18, John , 99.2

Click here for Quiz on Functions in Python

Spread the love
Lesson tags: program to count number of characters in file, python program to count number of lines in file, python program to count number of words in a file, read() function in python, Reading data from a file in python, readline() function in python, readlines() function in python
Back to: Python Programming Tutorial
Spread the love