How To Take File As Input From User In Python

In this tutorial, we will learn how to take a file as input from a user in Python. It is a common requirement to handle a variety of tasks like reading and processing data from files, storing input data for a program, etc. By the end of this tutorial, you’ll be able to take a user-provided file as input and read its content using Python.

Step 1: Fetching the File Path from the User

First, we need to get the file path from the user. We can use the input() function in Python for this purpose.

Make sure the user provides the complete file path, including the file name and extension (e.g., “C:/Users/user/Documents/sample.txt”).

Step 2: Opening and Reading the File

In Python, we can use the built-in open() function to open a file. The function returns a file object, which can be used to perform various operations on the file.

In the above code snippet, we are opening the file using the with statement, which ensures that the file will be properly closed after the nested block of code is executed. The "r" mode indicates that we want to open the file for reading.

We then use the read() function to read the content of the file and store it in the variable content. Finally, we print the content to the console.

Example File Content

Let’s assume we have a file called “sample.txt” with the following content:
Hello, this is a sample text file.
It contains a few lines of text.
Full Code

Here’s the complete code for reading a file from user input in Python:

Output

When you run the code and provide the path to “sample.txt”, you’ll see the following output:

Hello, this is a sample text file.
It contains a few lines of text.

Conclusion

In this tutorial, we learned how to take a file as input from the user in Python. We used the input() function to get the file path and the open() function to open the file for reading. We then used the read() function to read the file’s content and print it to the console. You can now use this technique to process user-provided files in your Python applications.