Python With As

In Python you can do the typical way of opening/writing to a file by calling it with: my_var = open(“my file.txt”,”r”) or “w” for write…

In such cases you need to close the file when you’re done with a my_var.close()

Instead you could also use:

with open(“my_file.txt”, “w”) as my_var:
my_var(“Write this to the file.”)

That will auto close it after executing.

Checking if a File is Open or Closed

To check if a file is open or not, you can use the method: closed

Example:

my_var.closed

Will return a boolean True (meaning closed) or False (meaning open.)

Python With As
User Rating: 0 (0 votes)