Plessix Stawn
Plessix Stawn

Reputation: 21

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

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?

Upvotes: 2

Views: 107

Answers (1)

iHowell
iHowell

Reputation: 2447

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

Upvotes: 1

Related Questions