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
		
while True:
	print("Enter 'x' for exit.")
	filename = input("Enter file name (with extension) to read: ")
	if filename == 'x':
		break
	else:
		c = open(filename, "r")
		print("\nThe file,",filename,"opened successfully!")
		print("The file contains:")
		print(c.read())
		c.close()
		print()

Here is the sample run of the above python program to illustrates how to read a file and display the content:

python read a file

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