简体   繁体   中英

How to close file_object in Python

I don't want to use the with operator right now. How can I achieve this using try-catch?

try: 
  file_object = open('todo.txt')
except FileNotFoundError: 
  print("The file is not found")
finally: 
  file_object.close() # file_object is not defined

UPDATE SOLUTION:

file_object = None 

try: 
  file_object = open('todo.txt')
except FileNotFoundError: 
  print("The file is not found")
finally: 
  if file_object is not None: 
    file_object.close() 

You could use else instead of finally . else triggers only if the code in the try block ran without any errors.

try: 
  file_object = open('todo.txt')
except FileNotFoundError: 
  print("The file is not found")
else:
  file_object.close() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM