Python File Reading

In this tutorial you will learn:

  • File Handling
  • File Handling in Python

File Handling

File Handling is an important concept to cover while learning any programming language. We need file handling to create, read, update or delete files. One of the biggest benefits of handling a file is that we can arrange data any way we want without requiring a specific template to follow. But using files for storing data works best for only small datasets. For larger datasets we may need to use a database.

File Handling in Python

We can also handle files in Python and it offers a simple syntax for that. We can read, create, update and write files in Python. Python either reads file as binary or as text. To write a file or to read from a file we need to follow three steps. The first thing that we need to do is to open a file, then we need to read or write to a file and then finally we need to close the file. Python offers the following modes for opening files.

Mode

Description

r

For reading a file

w

For writing or creating a file.

a

For appending to a file.

b

For opening a file in binary mode.

t

For opening a file in text mode.

+

For opening a file for reading or writing.

 

Example

The first step is to open a file and for that Python offers an open() function. We need to specify the

file = open(“myFile.txt", “r")

To read a file after opening we have three options. One option is to simply use the read method and then print the content.

print(file.read())

One option is to use readline function.

file.readline()

Another option is to use a for loop to print the contents of the file.

  1. for text in file:
  2. print(text)

Last step is to close the file using the close function.

file.close()

Add new comment