Hi Guys, welcome to my blog in this article you will learn about how to Write A Python Program To Read A File
Title :
Write A Python Program To Read A File
Description :
Hi guys, in this article you will learn a python program To read the contents of the file and print it to the standard output.
Use the input function call to ask a user to enter the file name and store it as string.
Use that try block to open the file in the read mode and read the contents of the file and store into another data variable, then close the file
Use the except block to catch the file not found error and print the message that the given file does not exist.
filename = input("Enter the file name: ")
try:
fd = open(filename, 'r')
data = fd.read()
fd.close()
except FileNotFoundError:
print("The File you entered does not exist")
Use the else block to print the contents of the file, print a sample user friendly message to signify the contents of the file is being printed. Then print the contents of the file using another print function call.
else:
print("Contents of file is ...")
print(data)
Complete Python Code :
filename = input("Enter the file name: ")
try:
fd = open(filename, 'r')
data = fd.read()
fd.close()
except FileNotFoundError:
print("The File you entered does not exist")
else:
print("Content of the file is ...")
print(data)
Output :
Enter the file name: sample.txt
Content of the file is ...
this is my sample text file
Output :
Enter the file name: code.txt
The File you entered does not exist
Conclusion :
The above Python program uses input function calls to ask a user to enter the file name and then use the file name string to open the file using the try block and then read the contents of the file.
Once the content is read, print the contents on to the standard output using the print function call.
Comment it down below if you have any suggestions to improve the above Python program
0 Comments