How to Read the Contents of a File in Python


In this example we will show how to get the file name and read the contents of the file.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

fileName = input("Enter the name of the file with .txt extension: ")
fileOpen = open(fileName, 'r')
lines = fileOpen.readlines()
for line in lines:
    print(line, end="")
print()
fileOpen.close()
Content of test1.txt:
line1
line2
line3

Output:

Enter the name of the file with .txt extension: test1.txt
line1
line2
line3
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments