codescracker


python

Python Program to Read a File



« Previous Program Next Program »


Read a File in Python

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.

Python Programming Code to Read a File

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:

read file python

And here is the screenshot of the content of the file, when you will open the file codescracker.txt:

reading a file python

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:

read file program python

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:

python program read file

Same program on python shell:

python read a file

Program Video with Compile and Run

Same Program in Other Languages

You may also like to learn or practice the same program in other popular programming languages:


« Previous Program Next Program »








Tools
Calculator

Quick Links
Signup - Login - Give Online Test