What can we write inside of a `with … as` code block?


#1

Question

What can we write inside of a with … as code block?

Answer

Any code you would normally write outside of a block to work with a file could be written inside of a with-as code block.
Just be sure to indent your code using 2 spaces (on Codecademy, anyway) per indentation level, otherwise Python won’t know that you intended for the code to be part of the with-as block. Failing to indent will cause an error if you try accessing anything you created inside of that code block, or trying to access the file variable.


Learn Python - File Input / Output - PSA: Buffering Data