Jan-28-2022, 01:09 AM
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.
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
Is this the compiler omitting to write the file because I didn't utilized the file/variable enough?
I ran into some strange behavior I don't understand while completing this online course. I was hoping you could help me understand it.
1 2 3 4 5 6 7 |
# 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() |
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())"1 2 3 4 5 6 7 8 |
# 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?