2

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?

2

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.