Monday, October 3, 2016

[ Exceptions & Files ] Working with Files

try:
    f = open("filename.txt")
    print(f.read())
finally:
    f.close()


This ensures that the file is always closed , even if an error occurs.


with open("filename.txt") as f :
   print(f.read())

This create a temporary variable (often called f) , which is only accessible in the indented block of the with statement.

No comments:

Post a Comment