In theory, the file should close when its finalizer is run, but that's not guaranteed to happen. You need to close the file to flush its buffer to disk, otherwise the data you "wrote" could hang in your Python script's memory.
The best way to ensure your file is closed is to use a with
block.
with open("C:\\Users\\foggi\\Documents\\Fred.txt", "w") as fp:
fp.write("Hello people")
Another good way is to just use pathlib
:
import pathlib
path = pathlib.Path("C:\\Users\\foggi\\Documents\\Fred.txt")
path.write_text("Hello people")
You could also close the file manually, but that's not recommended as a matter of style:
fp = open("C:\\Users\\foggi\\Documents\\Fred.txt", "w")
fp.write("Hello people")
fp.close()
The reason is because something might happen between open
and close
which would cause close
to get skipped. In such a short program, it won't matter, but in larger programs you can end up leaking file handles, so the recommendation is to use with
everywhere.