Hello guys. How are you all? I hope you all fine. In this tutorial we will learn about How to Print an Exception in Python. so without wasting time lets learn about of this.
How to print an Exception in Python
Print an Exception in Python
to print an Exception in Python Use this method to print an exception in python.
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'
How to print an Exception in Python
to print an Exception in Python Use this method to print an exception in python.
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'
python print exception
To print an Exception in Python Use this method to print an exception in python.
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'
Method 1:
Use this method.
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'
Method 2:
Use this method.
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'
Method 3:
Use this method.
with open("not_existing_file.txt", 'r') as text:
pass
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:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
Conclusion
It’s all About this Tutorial. Hope all methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you?
Also, Read