Reading from File

There are three ways to read data from a text file.

  1. read(): Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the entire file.
File_object.read([n])
  1. readline(): Reads a line of the file and returns in form of a string.For specified n, reads at most n bytes. However, does not reads more than one line, even if n exceeds the length of the line.
File_object.readline([n])
  1. readlines(): Reads all the lines and return them as each line a string element in a list.
File_object.readlines()

Note: ‘\n’ is treated as a special character of two bytes. 

Python3




# Program to show various ways to 
# read data from a file. 
   
# Creating a file
file1 = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
   
# Writing data to a file
file1.write("Hello \n") 
file1.writelines(L)
file1.close()  # to change file access modes
   
file1 = open("myfile.txt", "r+")
   
print("Output of Read function is ")
print(file1.read())
print()
   
# seek(n) takes the file handle to the nth
# byte from the beginning. 
file1.seek(0)
   
print("Output of Readline function is ")
print(file1.readline())
print()
   
file1.seek(0)
   
# To show difference between read and readline 
print("Output of Read(9) function is ")
print(file1.read(9))
print()
   
file1.seek(0)
   
print("Output of Readline(9) function is ")
print(file1.readline(9))
print()
   
file1.seek(0)
   
# readlines function 
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close() 


Output:

Output of Read function is
Hello
This is Delhi
This is Paris
This is London


Output of Readline function is
Hello


Output of Read(9) function is
Hello
Th

Output of Readline(9) function is
Hello


Output of Readlines function is
['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']

Note: To know more about reading from file click here.

Interact with files in Python

Python too supports file handling and allows users to handle files i.e., to read, write, create, delete and move files, along with many other file handling options, to operate on files. The concept of file handling has stretched over various other languages, but the implementation is either complicated or lengthy, but alike other concepts of Python, this concept here is also easy and short. The main focus of this article will be on the following topics.

  • Creating a file
  • Reading from file
  • Writing to file
  • Moving file
  • Deleting a file

Similar Reads

Creating a File

The first step in using a file instance is to open a disk file. In any computer language this means establishing a communication link between your code and the external file. To create a new file I/O classes provides the member function open(). Syntax:...

Reading from File

...

Writing to File

There are three ways to read data from a text file....

Moving File

...

Deleting a File

There are two ways to write in a file....