How do I use the with … as syntax?

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!

2 Likes

Is there any advantage to using the close() method instead? And is it normal to put a whole block of code under the “with…as…:” line? Or just one line like file_var.write(“Hello!”)?

1 Like

How to read from the file using the with..as method?
As the below code do not print anything in the console.

with open("text.txt", "r+") as my_file:
    my_file.write("Voldemort")
    my_file.read()
2 Likes

@lucifer27022004
after this:

with open("text.txt", "r+") as my_file:
    my_file.write("Voldemort")

the file pointer is currently pointing to the next space after

'Voldemort'

So when you say:

my_file.read()

python is reading the spaces, and not the words before it.

To read from the file, you need to create another with…as loop and then put it your read code.

Like this:

with open("text.txt", "r+") as my_file:
    my_file.read()

Here, when a file is opened, the pointer is starts reading from the beginning. So, all the content is read from the beginning.

An alternative to creating another with as is to use seek after writing to the file. Seek will take you to the byte in the file, so 0 would be the first byte, aka the start.

my_file.seek(0)