. Advertisement .
..3..
. Advertisement .
..4..
Python is a computer language widely used within programming, data science, and machine learning. It is a great computer language that is simple to learn and understand. It includes a plethora of development libraries and modules.
This article will give you some solutions on How to print an Exception in Python. We will describe it in the following paragraph shortly, so keep reading!
How To Print An Exception In Python?
Apply these methods to solve your problem.
for line in open("myfile.txt"): print(line, end="") Output : Traceback (most recent call last): File "e:\python tutorial\test2.py", line 1, in <module> for line in open("myfile.txt"): FileNotFoundError: [Errno 2] No such file or directory: 'myfile.txt'
with open("myfile.txt") as f: for line in f: print(line, end="") Output :
Traceback (most recent call last): File "e:\python tutorial\test2.py", line 1, in <module> with open("myfile.txt") as f: FileNotFoundError: [Errno 2] No such file or directory: 'myfile.txt'
The Methods
Method 1
Apply the following line of command.
for line in open("myfile.txt"): print(line, end="") With output: Traceback (most recent call last): File "e:\python tutorial\test2.py", line 1, in <module> for line in open("myfile.txt")
Method 2
Apply this following method.
with open("myfile.txt") as f: for line in f: print(line, end="") With output: Traceback (most recent call last): File "e:\python tutorial\test2.py", line 1, in <module> with open("myfile.txt") as f'
Method 3
Use the following method.
with open("not_existing_file.txt", 'r') as text: pass With output: Traceback (most recent call last): File "e:\python tutorial\test2.py", line 1, in <module> with open("not_existing_file.txt", 'r') as text
Conclusion
You may use our approaches to learn How to print an Exception in Python. We advised these three above solutions. However, you may implement the solution that best suits you.
Fill in the blanks in the feedback with any concerns or proposed answers so that we can better assist you. Thank you!
Leave a comment