3

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?

Devid Farinelli
  • 7,514
  • 9
  • 42
  • 73
JohnOfStony
  • 31
  • 1
  • 3

5 Answers5

3

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).

ergysdo
  • 1,139
  • 11
  • 20
  • Many thanks. That worked perfectly. Incidentally I did close the file in my original test, just forgot to post the "dtf.close"! – JohnOfStony Mar 27 '17 at 07:30
3

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")
Alex Fung
  • 1,996
  • 13
  • 21
2

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()
Community
  • 1
  • 1
bhansa
  • 7,282
  • 3
  • 30
  • 55
2

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.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
-1
dtf = open("C:\\Users\\foggi\\Documents\\Fred.txt","a+")
dtf.write("Hello people")

You can use this a+ as an alter

Dev Jalla
  • 1,910
  • 2
  • 13
  • 21