bob williams
bob williams

Reputation: 83

Python file closing safety

My code looks something like this:

with open(‘myfile.txt’, 'w+') as file:
    file.write("some stuff\n”)
    file.write(“some more stuff”)

The next line in my code opens a subprocess which reads from myfile.txt. I haven’t had any problems yet, but is this safe? Do I need to do something specific to ensure the file is closed so my subprocess won’t read the old version? Should I use Popen and the wait() command? If so, what is proper syntax? I haven’t seen any working examples.

Upvotes: 0

Views: 31

Answers (2)

CrizR
CrizR

Reputation: 688

By utilizing the "with" command you guarantee that after the code following the "with" command is executed, the file you opened will be closed. So, yes it's safe. That's one of the benefits of using it. This stack overflow answer explains it more thoroughly.

Upvotes: 0

user8840479
user8840479

Reputation:

This is completely safe. Using 'with ... as ...' automatically closes the file.

If you do not use 'with', you need to close the file manually.

Upvotes: 1

Related Questions