Python return file contents

Read File in Python

In this article, we’ll learn how to read files in Python.

In Python, temporary data that is locally used in a module will be stored in a variable. In large volumes of data, a file is used such as text and CSV files and there are methods in Python to read or write data in those files.

After reading this tutorial, you’ll learn: –

  • Reading both text and binary files
  • The different modes for reading the file
  • All methods for reading a text file such as read() , readline() , and readlines()
  • Read text file line by line
  • Read and write files at the same time.

Table of contents

Access Modes for Reading a file

To read the contents of a file, we have to open a file in reading mode. Open a file using the built-in function called open() . In addition to the file name, we need to pass the file mode specifying the purpose of opening the file.

The following are the different modes for reading the file. We will see each one by one.

Read text file

# read file with absolute path try: fp = open(r"E:\demos\files\read_demo.txt", "r") print(fp.read()) fp.close() except FileNotFoundError: print("Please check the path")
First line Second line Third line Fourth line Fifth line

An absolute path contains the entire path to the file or directory that we need to access. It includes the complete directory list required to locate the file.

Читайте также:  If array has index php

For example, E:\PYnative\files_demos\read_demo.txt is an absolute path to discover the read_demo.txt. All of the information needed to find the file is contained in the path string.

While opening a file for reading its contents we have always ensured that we are providing the correct path. In case the file not present in the provided path we will get FileNotFoundError .

We can avoid this by wrapping the file opening code in the try-except-finally block.

Reading a File Using the with Statement

We can open a file using the with statement along with the open function. The general syntax is as follows.

with open(__file__, accessmode) as f:

The following are the main advantages of opening a file using ‘with’ statement

  • The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks.
  • This also ensures that a file is automatically closed after leaving the block.
  • As the file is closed automatically it ensures that all the resources that are tied up with the file are released.

Let us see how we can the with statement to read a file.

# Reading files using 'with' with open('read_demo.txt', 'r') as file: print(file.read())
First line Second line Third line Fourth line Fifth line

File Read Methods

Python provides three different methods to read the file. We don’t have to import any module for that.. Below are the three methods

Text file after read and write operation

Reading File in Reverse Order

We can read the contents of the file in reverse order by using the readlines() method and then calling the reversed () method on the list to get the contents of the list in reverse order. We can then iterate over the contents of the list and print the values.

with open('readdemo.txt', 'r') as f: lines = f.readlines() for line in reversed(lines): print(line)
Fifth Line Fourth Line Third Line Second Line First Line

Reading a Binary file

Binary files are basically the ones with data in the Byte format (0’s and 1’s). This generally doesn’t contain the EOL(End of Line) so it is important to check that condition before reading the contents of the file.

Читайте также:  Python text file as list

We can open and read the contents of the binary file using the ‘with’ statement as below.

with open("Timezones.jpg", "rb") as f: byte_content = f.read(1) while byte_content: #Printing the contents of the file print(byte_content)

We have seen in this post how the file contents could be read using the different read methods available in Python. We also saw few simple examples to read the contents partially like first few lines or last few lines based on our requirement.

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

Оцените статью