Python Text File Read and Show Contents Program

By | August 13, 2019

Task: Python Text File Read and Show Conetents Program. 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 File Program To Read and Show Contents of  a Text File

Python File Program To Read and Show Contents of  a Text File

The source code of Python Text File Read and Show Conetents Program.

 

# 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
# on D drive.

# open mytext.txt file in read mode
file1 = open("d:/mytext.txt", "r")

# Read all contents of text file in a string s

s = file1.read()

# show the contents from string s

print(s)

# close the text file
file1.close()

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.

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

One thought on “Python Text File Read and Show Contents Program

  1. Pingback: Python file program read numbers write squares | EasyCodeBook.com

Leave a Reply

Your email address will not be published. Required fields are marked *