TestingDocs.com
Software Testing website
  • Automation
    • Selenium
    • JBehave Framework
  • Tutorials
    • MySQL Tutorials
    • Testlink
    • Maven
    • Git
  • IDEs
    • IntelliJ IDEA
    • Eclipse
  • Flowcharts
    • Flowgorithm
    • Raptor
  • About

Python

Read file in Python

Python Tutorials

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:

Python File Process Command

Related Posts

Download Python Windows 11

Python /

Download & Install Python on Windows 11

PyCharm CE

Python /

Install PyCharm on Ubuntu Linux

Python Install on CentOS Linux

Python /

Install Python on CentOS

What is Python?

Python /

What is Python?

Install Python

Python /

Install Python 3.6 on Windows

‹ Python Turtle Graphics› Running a Python Selenium Script

Recent Posts

  • MS Access Data Types
  • Install RAPTOR Avalonia on CentOS
  • Download RAPTOR Avalonia Edition on Windows
  • npm doctor command
  • Build & Run CLion Project
  • Create New CLion C Project on Windows
  • Configure CLion Toolchains on Windows
  • Launch CLion IDE on Windows
  • Activate CLion IDE
  • CLion IDE for C/C++ Development

Back to Top

Links

  • Contact
  • Privacy Policy
  • Cookie Policy

www.TestingDocs.com

Go to mobile version