How to Take Input from a Text File in Python

Do you need to read a text file using Python? You’re in the right place. Today we’ll be diving head-first into how to get Python to take input from a text file. Let’s get started.

Step 1: Creating a Text File

First, we have to create a text file to take input from. You can create a text file in many ways, the easiest is probably using a basic text editor like Notepad or TextEdit. Here is an example of a text file’s content:

Hello, World!
This is a sample text file.
It contains three lines.

Let’s say we name this file “sample.txt” for the purpose of this tutorial.

Step 2: Opening the File in Python

In order to read a file using Python, we use the open function. This function requires two arguments: the file path and the mode. In our case, the mode will be ‘r’ for read mode.

Step 3: Reading the File

Now, we will read the file using the read function. This function returns the entire content of the file as a single string.

This will read and print the entire content of the file.

Step 4: Closing the File

Always remember to close the file after reading using the close method. It is crucial to make a habit of this to prevent memory leaks and avoid keeping resources in use when they don’t need to be.

Here is the complete code:

When we run the code, here’s the output:

Hello, World!
This is a sample text file.
It contains three lines.

Conclusion

As we have seen, reading file input in Python is quite straightforward and simple. It’s important to adopt good habits by closing files when we’re done with them to conserve system resources. Remember, practice makes it even easier, so play around with this feature and it will become second nature. Happy coding!