Behavior of read() and readlines() in Python

39 Views Asked by At

A functionality for writing automatically into a markdown file with Python has a bizarre behavior that I don't understand, so I'm trying to write it anew with tests. (I'm using the latest version of Python.)

I have the following code, super simple, which is the very beginning of the file writing :

def add_new_line(file : str):
    with open(file, 'r') as fr:
        file_content = fr.read()
    
        with open(file, 'a+') as fw:
            if file_content != "" and not file_content.endswith("  \n"):
                fw.write("  \n")

if __name__ == "__main__":
    with open("markdown_test.md", 'a+') as fw:
        fw.write("TEST")

    add_new_line("markdown_test.md")

    with open("markdown_test.md", 'r') as fr:
        lines = fr.read()

Most of this code is here for me to try to understand something :
I'm writing the first line "TEST" in a file, and then enter the function in which I'm checking if it ends with " \n", in which case markdown will put new content on a new line.
When I enter my function, open my file et read it, my debugger informs me that fr.readlines() actually reads "TEST". On the other hand, the line "file_content = fr.read()" is always equal to an empty string, therefore not adding the necessary characters at the end of the line.

Going out of that function, I try to read the file again, for a double check, and once again, fr.read() returns an empty string even though it should read "TEST".

I found this behavior while checking in a test if fr.read().endswith(' \n') was true. It was, but the test always failed, so I wanted to investigate further.

Could someone enlighten me on what's happening here ?

Thank you for your attention !

0

There are 0 best solutions below