How do I use the with … as syntax?


#1

Question

How do I use the with … as syntax?

Answer

As an example, the only code you need on a line is this:
with open(“file.txt, "mode") as file_var:
Then, inside the block of code on the next line, you use your file however you choose by accessing the file object through the file_var you just created.
Be sure not to write anything else on the with … as line shown above, and to indent your code properly inside using 2 spaces per indentation level.
An example file operation you could perform inside would be file_var.write("Hello!"). And since we’re using the handy with … as syntax, we don’t need to close() our file anywhere!


Learn Python - File Input / Output - Try It Yourself