Task: Python Text File Read and Show File. This Python programming tutorial will use open(), read() and print() functions to read and display the whole contents of a text file on the drive D.
First of all, we assume that the text file mytext.txt already exist on the D drive. Otherwise you can use notepad in Microsoft Windows to create a new text file. Type the following contents in this file and save it with the name “mytext”.
Python program to open , read and display file
The source code of Python Text File Read and Show Conetents Program.
The output of This Python File program is:
This is a text file. I wish to read and display the contents of this text file on the standard output device - a monitor screen. I created this file using the Notepad text editor in Microsoft Windows. This is the second paragraph in this text file. Simply read() function is used to read all contents of a text file and assign to a string variable. We can print the contents of the file using print() function.
How this File program works?
Write a Python program to open an existing file mytext.txt from D drive.
The program will read and show the contents of this text file
- First of all Open mytext.txt file in read mode
- Read all contents of text file in a string s using read() method of file object.
- Note that the read() method will read whole text of file and reurn it, which is stored in a string variable named s.
- Use print() function to show the contents from string s
- After printing the contents of the file we must Close the text file.
- In tihis way this Python program is terminated.
You may also like to read:
Python File Programs – Python File Handling
Write a Python file program read numbers write squares.
Python Text File Read and Show Contents Program
Python Text File Read and Display file data with Exception Handling FileNotFoundError
Python File Program Count Characters in Text File
Python Text File Program To Count Vowels