Maanish
Maanish

Reputation: 99

Writing to a file and function

I have a code similar to:

'''
This is main file
'''

path_to_file = './sample.txt'
config_file = open(path_to_file, 'a')
import functions_write as function
a = 1
if a== 1:
    config_file.write("Hello World\n")
    function_text = "Hi World\n"
    function.write_function(function_text, path_to_file)
#

Another file for writing functions functions_write.py

def write_function(text_write, path_to_file):
    config_file = open(path_to_file, 'a')
    config_file.write(text_write)
    config_file.close()

#################################################################

I had expected it would write in order

Hello World Hi World

But it is writing as: Hi World Hello World

Any thoughts on why it is writing the function first in the file.

Thanks

Upvotes: 2

Views: 61

Answers (1)

Turn
Turn

Reputation: 7040

You shouldn't generally have two open write file descriptors to a file as you do. What's happening here is that writes are buffered until something causes them to get flushed. In this case you explicitly call the close in write_function so it is called (and that write gets flushed) first. The first write isn't flushed until the close on its file descriptor is implicitly closed when your program exits.

Upvotes: 3

Related Questions