close

How to print an Exception in Python

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

  1. 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'

  2. 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'

  3. 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

Leave a Comment