×

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 Tuple Methods

Python Tuple Methods Python has two built-in methods that are used for tuples. The following are the two methods: Method Description count() The tuple.count() method in Python returns the number of times a...

1 minute read.

Cursor in Python

The cursor is an item that aids in query execution and records retrieval from databases. The cursor is crucial to the execution of the query. In-depth information on the execution...

7 minutes read.

Python Set Methods

[et_pb_section][et_pb_row][et_pb_column type="4_4"][et_pb_text] Python Set Methods A set is a collection which is unordered and unindexed. Python has a set of built-in methods that you can use on sets. Methods ...

4 minutes read.

Find whether the given stringnumber is palindrome or not

Problem statement Sam is found of playing with strings. One day he thought of finding whether a string is a palindrome or not. He wanted to develop a computer process to...

2 minutes read.

Difference between Module and Package in Python

The main difference between the module and the package in Python is that the module can be a simple file in Python that contains the different functions and collection of...

4 minutes read.

Python String split() method

The string.split() method in Python splits a string into a list and returns a list of the words in the string. If the parameter maxsplit is given, at most maxsplit splits are done. If maxsplit is...

2 minutes read.

Check Palindrome in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

4 minutes read.

How to plot a Histogram in Python

A Histogram is used to represent a given data provided as a chunk. This histogram is a graphical representation that uses bars to indicate the ranges of the data. In...

4 minutes read.

End Parameter in python

print(): The python print() function prints the program’s output to the output screen. The output can be an integer value, string value or other value. Syntax: print(“hi”) Output: hi will be displayed on the output...

3 minutes read.

How To Install Python In Ubuntu

How To Install Python In Ubuntu Ubuntu is free and open-source software and it is an essential part of the Linux distribution. It is a popular operating system developed by Canonical. If we...

3 minutes read.

How to assign values to variables in Python and other languages?

Python makes it simple to construct variables. The value to be stored in the variable should then be written after a suitable name for the variable and the equality sign....

3 minutes read.

Python round() function

Python round() function The round() function in Python returns a number rounded to ‘ndigits’ precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input. Syntax round(number[, ndigits]) Parameter Number: This parameter represents the...

1 minute read.

Python List sort() method

The list.sort () method in Python sorts the items of the list in place. Syntax list.sort(key=None, reverse=False) Parameter reverse: If a Boolean value ‘True’ is passed, the  sorting will be done in the descending order else for ‘False’...

2 minutes read.

Python IDE names

Python is one of the most renowned programming languages. It has different execution conditions and a great many compilers to execute the python programs, e.g., PyCharm, PyDev, Jupyter Notebook, Visual...

6 minutes read.

Python Built-in Functions

Python Built-in Functions The Python interpreter has a number of functions and types built into it that are always available. The Python built- in functions are as follow: Methods Explaining abs() The abs() function returns...

6 minutes read.

Import py file in Python

In Python programming language, a module is a single layer of block of Python code that can be loaded and used by importing into other Python block of code. A module...

4 minutes read.

Python String lower() method

Python String lower() method The string.lower() method in Python returns a string where all characters are lower case. Syntax string.lower() Parameter NA Return This method returns a string where all characters are lower case. Example 1 # Python...

1 minute read.

Iterators in Python

Introduction In Python, an iterator is defined as an object that enables traversing through all the values of a collection. It contains the countable number of values. The iterator is utilized to...

4 minutes read.

How to slice a list in python

When working with lists, we face situations where we may need a part of the list from one index to the other. Slicing is one of the simpler ways to...

5 minutes read.

Word frequency Python

Word frequency Python In this tutorial, we will write the Python program to count the occurrence of a word (word frequency) in a given sentence. We will learn all the approaches...

5 minutes read.