kozjava
kozjava

Reputation: 47

os.path.getsize() returns "0"

Getting "0" output, when I am trying to use os.path.getsize()

Not sure what's wrong, using PyCharm, I see that the file was created and the "comments" were added to the file. But PyCharm shows the output "0" :(

Here is the code:

import os
def create_python_script(filename):
  comments = "# Start of a new Python program"
  with open(filename, "w") as file:
    file.write(comments)
    filesize = os.path.getsize(filename)
  return(filesize)

print(create_python_script("program.py"))

Please, point what is the error I don't see.

Upvotes: 0

Views: 2728

Answers (1)

Rohit Lal
Rohit Lal

Reputation: 3349

You're getting the size 0, due to the peculiar behaviour of the write function.

When you call the write function, it writes the content to the internal buffer. An internal buffer is kept for performance constraints (to limit too frequent I/O calls).

So in this case, you can't ensure that the data/content has been actually dumped to the file on disk or not when you call the getsize function.

with open(filename, "w") as file:
    file.write(comments)
    filesize = os.path.getsize(filename)

In order to ensure that the content is dumped to the file before calling the getsize function, you can call flush method.

  • flush method clears the internal buffer and dumps all the content to the file on the disk.
with open(filename, "w") as file:
    file.write(comments)
    file.flush()
    filesize = os.path.getsize(filename)

Or, a better way would be to first close the file and then call the getsize method.

with open(filename, "w") as file:
    file.write(comments)
filesize = os.path.getsize(filename)

Upvotes: 1

Related Questions