×

Read Text files in Python

In Python, there are many ways to read text files. Before going into the detailed structure of reading a text file, let us understand how reading text files takes place with an easy example.

Example:

Consider that you want to read a book. To read a book, you are supposed to open it first. Then you can start reading, i.e., perform read operation/activity. When you're done reading, you'll not leave the book open, right? You'll close the book as soon as you complete reading. In the same way, reading of a text file will be performed in python. Let's now go over the detailed procedure for reading a text file.

The procedure followed for reading a text file:

1. Opening the text file:

  • We need to use the open () function/method to open the text file.
  • The function opens the text file and allows the user to perform any operation.

Syntax of open ()

open (filepath, mode) 

As we all know, the characters inside the parenthesis of the method/function are known as Parameters. "filepath" and "mode" are Parameters defined within the method. Here, "filepath" is the file's path where it is stored. You can copy the path of the file when the file is opened, as shown in the figure below.

Read Text files in Python

Mode is defined depending on the operation that you want to perform.

  • In order to perform a "read" operation, the mode should be taken as 'r'.
  • In order to perform a "write" operation, the mode should be taken as 'w'.
  • In order to perform an "append" operation, the mode should be taken as 'a'.

Let's open a text file in a read mode with an example program:

f = open (“D:\downloads hdd\certificates”,’r’)

The text file “certificates” in the “downloads hdd” folder will be accessed and opened with this code.

2. Reading the text file:

  • The read operation can be performed on a text file in 3 ways.
  • If the given file is of small size and you want to convert all the text into a string as a whole, then the read() method must be used.

Syntax:

var.read()
  • If you want to read the text file line after line and return all the lines in a string format, then the readline() method must be used.

Syntax:

var.readline()
  • If you want to read all the lines at a time and the text to be represented as a list of strings, then the readlines() method must be used.

Syntax:

var.readlines()

( The variable “var” must be assigned with the "open method” of the text file before calling “read method “. )

4.Closing the text file:

  • After reading the text file, the final operation is to close the file by using the close() method.
  • It is mandatory to close the file as soon as the work is completed in order to prevent unnecessary access. 
  • It is safe if you close the files after usage.
  • Syntax of close() :
var.close()
  • You can close the file without using the close() method also. By using the "with" statement, the text file will be automatically closed.
  • Syntax of “with”:
with open(filepath,mode) as var1:


	  var2 = var1.readlines() 
  • The variable need not call “close method” now as there is an automatic close reflex “with” to close the file.

Example programs determining opening, reading, and closing operations:

1. Using readline()

    f = open (“D:\downloads hdd\certificates”,’r’)
     x = f.readline()
     y = f.readline()
     z = f.readline()
     print(x) 
     print(y) 
     print(z) 
     f.close()

Output:


    I have achieved a SoloLearn Certificate in Python.




    I have achieved CISCO Certificate in Python.




    I have achieved a Hackerrank Certificate in Python.

Explanation:

Initially, the file is opened and is assigned to a variable "f". There are 3 lines of text present in the file. To print 3 lines, we should read 3 lines separately (if we use readline() ), assigning that operation to the respective variables "x", "y", and "z". These 3 variables are printed separately.

2. Using read() and “with”

with open (“D:\downloads hdd\certificates”,’r’) as f:
    	x = f.read()
    	print(x) 

Output:

I have achieved a SoloLearn Certificate in Python.
I have achieved CISCO Certificate in Python. 
I have achieved a Hackerrank Certificate in Python.

Explanation:

Initially, the file is opened as f using ”with”. There are 3 lines of text present in the file. To print 3 lines, we read 3 lines as a whole (if we use read() ), considering it as a single content assigning that operation to the respective variable “x”. The variable x is printed. So, 3 lines are printed as a whole.   

3.Using readlines()

f = open (“D:\downloads hdd\certificates”,’r’)
x = f.readlines()
print(x) 
f.close()

Output:

[‘I have achieved SoloLearn Certificate in Python.’,


    ‘I have achieved CISCO Certificate in Python.’,


    ‘I have achieved Hackerrank Certificate in Python.’]

Explanation:

Initially, the file is opened and is assigned to a variable "f". There are 3 lines of text present in the file. To print 3 lines, we read all 3 lines once (if we use readlines() ), considering that the file consists of more than one line and assigning that operation to the respective variable "x". The variable x is printed. The file is closed. So, 3 lines are printed one after another at a time in a list of string format.

This is how the reading of a text file takes place. Depending on the read function we use, the output format varies.


Related Topics

Python String rjust() method

Python String rjust() method The string.rjust() method in Python returns a right-justified string of a given minimum width where the padding is done using the specified fillchar (default is a space). It returns...

2 minutes read.

Python oct() function

Python oct() function The oct() function in Python converts an integer number to an octal string prefixed with “0o”. Syntax oct(x) Parameter x: This parameter represents an Integer Number Return This function returns an octal string. Example 1 #...

1 minute read.

Python elif

Python elif The elif statement is used to check multiple conditions and execute the specific block of statements depending upon the true condition among them. Syntax if expression1: statement elif expression2: statement elif expression3: statement else: statement The elif statement can be optional...

3 minutes read.

Python JSON

In this tutorial, we will learn about JSON in the Python programming language. We will focus on its features, Guidelines to be kept in mind while writing its syntax, the...

3 minutes read.

Python Os sep

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Exclusive OR in Python

In Python, the exclusive OR (XOR) operator is represented by the caret symbol (^). It compares each bit of the first operand to the corresponding bit of the second operand,...

3 minutes read.

Python Program to Check Leap Year

Python Program to Check Leap Year Leap year: We all know that each year has 365 or 366 days. But whenever a year has 366 days, then the year is said...

2 minutes read.

Features of Python

Python is a powerful, easy to learn, popular programming language. It has effective data structures and its elegant syntax makes it user-friendly language. Below are the key features of Python: 1. Python...

4 minutes read.

List in Python

What is List in Python In Python, lists are used to store the multiple values in one variable. We can say that list is the collection of similar as well as...

3 minutes read.

Python Argmin

Introduction The argmin function is defined as numpy.argmin(). This function returns the index of the minimum value or element from a Numpy array in a specific axis. An array is taken...

3 minutes read.

Python List index() method

Python List index() method The list.index () method in Python returns the position at the first occurrence of the specified value. Syntax list.index(x[, start[, end]]) Parameter element – This parameter represents the element whose lowest index will be returned. start (Optional)...

2 minutes read.

Python Dictionary setdefault() method

Python Dictionary setdefault() method The dictionary.setdefault () method in Python returns the value of the item with the specified key. Syntax dictionary.setdefault(keyname, value) Parameter keyname- This parameter represents the keyname of the item you want...

1 minute read.

Python Simple Interest

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

3 minutes read.

Cross Entropy in Python

Introduction Cross-entropy loss is frequently combined with the softmax function. Determine the total entropy among the distributions or the cross-entropy, which is the difference between two probability distributions. For the purpose...

5 minutes read.

Python MongoDB Tutorial

An Introduction to MongoDB MongoDB is a document-oriented database application. It is an Open-source and platform-independent program. MongoDB is similar to few NoSQL databases that store the data in the documents...

17 minutes read.

Python Selectors

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

4 minutes read.

Python Assert

Python Assert Python provides an assert statement which is used to check the logical expression. If the given logical expression is true, then it precedes for the next line; otherwise, it raises an...

2 minutes read.

Python Data Types

Python Data Types: The variable in Python is used to store values, and they can hold different values. Each variable in Python has its own data-type. Since Python is a...

13 minutes read.

Python String zfill() method

Python String zfill() method The string.zfill() method in Python returns a copy of the string while adding the zeros (0) at the beginning of the string, until it reaches the specified...

1 minute read.

Decision Tree in Python

Decision Tree is one of the most essential algorithms in the area of machine learning for classification and regression. But let us first talk about the lifespan of every machine learning...

12 minutes read.