Program for reading data from file and displaying onto monitor

In this blogs, we will read data from text file and display onto screen. Text file contain list of city names.

Our filename is test.txt and below is the content of file that we need to read and display it

Create a file handler that points to our text file. Use ‘r’ mode with open function. ‘r’ is for reading content from file

file = open("C:/Users/rohit/Desktop/test.txt",'r')

Use read() method to read data from a file. Below statement will read content from the file and will store it in cities variable

cities = file.read()

Now use print() function to display content of cities variable

print(cities)

Close the file

file.close()

Output

New York
London
Paris
Berlin
Bogota
Tokyo
Stockholm
Mumbai
Sao Paulo
Moscow
Karachi
Singapore
Sydney

Complete Code

file = open("C:/Users/rohit/Desktop/test.txt",'r')
cities = file.read()
print(cities)
file.close()
Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s