AnsweredAssumed Answered

What is Best Way to Handle Files in Python

Question asked by pmckinneyccpa on Jun 13, 2017
Latest reply on Jun 15, 2017 by CDow-esristaff

I often write the results of geoprocessing scripts to a text file.  After doing some research, I learned I'm not using best practices for closing the file.  I'm not opening the file using the with keyword, so the file may not close if there is an error.  If there is an error, I need to be able to write the error message to the text file.  It looks like I could use the finally keyword or with keyword to ensure the file closes.    

 

Which of these options is better? And if I've made any errors in how I think I could improve my implementation, please let me know. Thanks!  

 

Method #1

try:
   # log file to write to
   logFile = r'path\tofile\fileName.txt'

   # open file in write mode
   report = open(logFile, 'w')

   # geoprocessing stuff

   # write to report
   report.write('some message')

except Exception as e:
   # get line number and error message
   report.write('an error message')

finally:
   report.close()

   

Method #2

 

try:
   # log file to write to
   logFile = r'path\tofile\fileName.txt'
  
   # open file in write mode
   with open(logFile, 'w') as f:
      # geoprocessing stuff
  
      # write to report
      f.write('some message')

except Exception as e:
   # get line number and error message
   with open(logFile, 'a') as f:
      f.write('an error message')

Outcomes