Do we need to handle error for open file with write and while writing lines?

244 Views Asked by At

While reading a string from file, we use the below python code where we need to handle the error.

try:
  input_file = open("ABC.txt","r")
  input_file.close()
except IOError:
  print("IO Error")

But if we want to write data to a file, do we need to handle error?

How come python does not throw error, It could happen user might not have write access to create a file at a specific location. From the documents it says If we use "w", it creates a file if it does not exists.

Why does it never fail? Usually in most languages we handle both read and write error.

output_file = open("DEF.txt","w")
items_to_write = ["a","2","c"]
output_file.writelines(items_to_write)
0

There are 0 best solutions below