Site icon TestingDocs.com

Read file in Python

Introduction

In this post, we will see how to read a file and print its contents using Python. We will enclose the file open command within try/except block. We may need to wrap the file open assuming that it might fail and add recovery code when the file open fails. The exit() function terminates the program. It is a function that we call that never returns. Optionally, we can close the file which we open for reading with close() command.

Below is a sample code snippet to open and process file contents:

Python Code

#Open file
fileName = input('Enter the file name:')
try:
fileID =open(fileName)
except:
print('File cannot be opened:', fileName)
exit()

#Count initialized to zero
count=0

print('File Contents:')
print('***********************************') 
#Process the file
for line in fileID:
count=count + 1
print(line)

#Print line count
print('***********************************') 
print('Number of lines in the file are: ', count)

#Close the file
fileID.close()

 

File Contents: ( week.txt)

———————–

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

Output

Enter the file name:week.txt
File Contents:
***********************************
Monday

Tuesday

Wednesday

Thursday

Friday

Saturday

Sunday
***********************************
Number of lines in the file are: 7

Screenshot

In the program, we have printed all the file contents and counted the number of lines in the input file. Screenshot of the program below:

Exit mobile version