How does os.path.getsize() work within a "with" block in Python?

Viewed 22

The fun(filename) function creates a new file passed to it as a parameter, adds some text and then returns its size. When print(os.path.getsize(filename) is used within the 'with' block it doesn't work as intended.

import os

def fun(filename):
    with open(filename,'w') as file:
        file.write("hello")
        print(os.path.getsize(filename))

fun("newFile2.txt")

It outputs 0. But when print(os.path.getsize(filename) is used outside the 'with' block as

import os

def fun(filename):
    with open(filename,'w') as file:
        file.write("hello")
    print(os.path.getsize(filename))

fun("newFile2.txt")

Then it prints the correct output: 5. What's going on behind the scenes?

1 Answers

This is due to the buffered nature of writing to files. When you close the file, i.e., exit the with block, the rest of the buffered input gets written to the file. You can read more about python buffering modes used in open here: https://docs.python.org/3/library/functions.html#open

Related