Reputation: 31
The code I've tried is:
dtf = open("C:\\Users\\foggi\\Documents\\Fred.txt","w")
dtf.write("Hello people")
This works fine on Android (with appropriate changes to the file path) but under Windows 10 it creates an empty file. How can I overcome this?
Upvotes: 3
Views: 9304
Reputation: 1159
You have to close the file, after you are done writing to it.
dtf = open("C:\\Users\\foggi\\Documents\\Fred.txt","w")
dtf.write("Hello people")
dtf.close()
Or, preferably:
with open("C:\\Users\\foggi\\Documents\\Fred.txt","w") as dtf:
dtf.write("Hello people")
You can read more about the with
block, including how to create your own objects which you can use with with
, here: http://preshing.com/20110920/the-python-with-statement-by-example/ (first Google result).
Upvotes: 3
Reputation: 7504
You need to close the file if you want to see the changes:
I use with
always, it closes the file when the block ends.
with open("C:\\Users\\foggi\\Documents\\Fred.txt","w") as fs:
fs.write("Hello people")
Or just close the file when you are finish writing. Use file.close()
dtf = open("C:\\Users\\foggi\\Documents\\Fred.txt","w")
dtf.write("Hello people")
dtf.close()
Upvotes: 2
Reputation: 2006
The reason the file is empty is because you did not close the file object before opening it.
It is recommended to open files with with
most of the time as it closes the file object for you behind the scene:
with open("C:\\Users\\foggi\\Documents\\Fred.txt","w") as f:
f.write("Hello people")
Upvotes: 3
Reputation: 213318
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.
Upvotes: 2
Reputation: 2489
dtf = open("C:\\Users\\foggi\\Documents\\Fred.txt","a+")
dtf.write("Hello people")
You can use this a+ as an alter
Upvotes: -1