To read a file in python, you have to ask from the user to enter name of a file along with their extension to open and read all the content present inside that file and display the content of the same file on the output screen as shown in the program given below.
Following python program ask from the user to enter the file's name to read and display the content of the file and finally closes the file:
# Python Program - Read a File print("Enter 'x' for exit."); filename = input("Enter file name (with extension) to read: "); if filename == 'x': exit(); else: c = open(filename, "r"); print("\nThe file,",filename,"opened successfully!"); print("The file",filename,"contains:\n"); print(c.read()) c.close()
Let's suppose we have a file created inside the current python directory named codescracker.txt with following contents inside it:
I am First Sentence of codescracker.txt. I am Second Sentence of codescracker.txt. I am Third sentence of codescracker.txt.
Here is the screenshot of the file present inside the folder python:
And here is the screenshot of the content of the file, when you will open the file codescracker.txt:
Now let's run the above program.
Here is the sample run of the above python program to illustrates how to read a file and display the content:
Now let's enter the file name say codescracker.txt which is already present inside the current python folder with some content inside it, and press enter key to read all the content present inside the given file:
Same program on python shell:
Program Video with Compile and Run
You may also like to learn or practice the same program in other popular programming languages: