Python Forum

Full Version: Strange write()/File behavior
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everyone,
I ran into some strange behavior I don't understand while completing this online course. I was hoping you could help me understand it.

# Reading and writing at the same time
in_file = open('c:/users/*****/desktop/mydata.txt', 'r+')
print(in_file.readline())
in_file.seek(0)
in_file.write('Hi!')
print(in_file.readline())
in_file.close()
The file mydata.txt contains the text "Hello\nWorld!".
In the above code, for reasons I don't understand, it doesn't write to the file. I would have expected it to write "Hi!" over the first three characters and then print the remaining characters "lo", but instead it doesn't write at all and the second readline() prints "Hello" a second time

Output:
Hello Hello
So I wanted to figure out why it wasn't working and decided to add the line "print(in_file.tell())"
# Reading and writing at the same time
in_file = open('c:/users/*****/desktop/mydata.txt', 'r+')
print(in_file.readline())
in_file.seek(0)
in_file.write('Hi!')
print(in_file.tell())
print(in_file.readline())
in_file.close()
Output:
Hello 3 lo
Well now it works as expected. But it only works if I use either tell() or seek() on it after the write() keyword. This works for my assignment because I was required to seek() back to the beginning of the file anyway, but I'm curious why it doesn't write at all in the first example.

Is this the compiler omitting to write the file because I didn't utilized the file/variable enough?
This is an OS/stdio library thing and python doesn't do anything to modify the behavior.

If you have a file you're both reading and writing, you need to flush the buffer or reposition between operations Something like seek(tell(...)) would be fine. You'd have the same limitation in C.

Basically you executed the write(), but it's written to a buffer rather than the file itself. Then when you read() you updated the buffer pointer. Later when the file was closed, the write() buffer is flushed and it wrote at the new position rather than where you intended. Your file was being updated, but since you only printed the first line you didn't notice.

An in_file.flush() after the write and before the read would also work.
Thanks for your reply.

After you mentioned flush() I remembered it was mentioned earlier in my lesson. I went back and reread that section.

Thanks again for the help :-)