How To Take Input From A File In Python

In this tutorial, we will learn how to take input from a file in Python. Reading files is an essential skill for any programmer and is especially useful when dealing with data analysis, configuration files, or input data for your program. Python provides easy-to-use functions that allow you to read data from a file with minimal effort.

Step 1: Create a sample input file

Before we start reading data from a file, let’s first create a sample input file. In this example, we will use a simple text file containing the following data:

Apple
Banana
Cherry
Date

Save this data in a text file named fruits.txt in your working directory.

Step 2: Open the file in Python

In order to read data from a file, you need to first open the file in Python. You can use the built-in open() function to open the file. The open function takes two arguments: the name of the file and the access mode, which determines whether you want to read or write data to the file.

In this tutorial, we will use the ‘r’ mode to open the file, which means the file is opened for reading.

Step 3: Read the data from the file

There are several methods to read data from a file. Let’s discuss some common methods:

  1. read(): This method reads the entire contents of the file and returns a string.
  1. readline(): This method reads a single line from the file.
  1. readlines(): This method returns a list containing all the lines of the file.

Step 4: Close the file

After you are done reading data from the file, it is a good practice to close the file using the close() method. This helps in freeing up system resources and prevents possible file corruption.

For the above-mentioned methods, here is the complete code to read the data from the file:

Output:

Step 5: Use a context manager to handle files

A more efficient way to handle files in Python is using a context manager, which automatically takes care of opening and closing the file for you. The with keyword is used to create a context manager. Below is an example of how to read data from a file using a context manager:

In this case, you don’t have to explicitly call the close() method, as the context manager takes care of it.

Conclusion

In this tutorial, you have learned how to read data from a file in Python using various methods such as read(), readline(), and readlines(). The context manager is the more efficient way to handle files in Python, as it takes care of opening and closing the file automatically.