I have implemented two methods to read a file in python. The one uses the os module while the other uses try-except. Which of the two you believe is the best and why?
import os
path1 = "C:\Users\kompo\Desktop\p train\hi.txt"
path2 = "C:\Users\kompo\Desktop\p train"
#method1
if os.path.exists(path1):
print("exists")
if os.path.isfile(path1):
print("is file")
with open(path1) as file:
print(file.read())
print(file.closed) #check if closed
elif os.path.isdir(path1):
print("is dir")
else:
print("does not exist")
print("==================================")
#method2
try:
with open(path1) as file:
print(file.read())
print(file.closed) #check if closed
except FileNotFoundError as e:
print(e)
print("does not exist")
except PermissionError as e:
print(e)
print("is dir")
except Exception as e:
print(e)
print("unexpected exception")
New contributor
Hector Kobos is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.