Joshua Schlichting
Joshua Schlichting

Reputation: 3450

Python 3.6 - file.write() not actually writing

In case you didn't catch it in the title, this is Python 3.6

I'm running into an issue where I was able to write to a file, and now I cannot. The crazy thing is that this was working fine earlier.

I'm trying to either append my file if it exists, or write to a new file if it doesn't exist.

main_area_text represents the div tag text below

<div id="1131607" align="center" 
style="width:970px;padding:0px;margin:0px;overflow:visible;text-
align:center"></div>

and below is my code:

main_area_text = #this is equal to the html text above
                 #I've verified this with a watch during debugging
                 #But this doesn't actually matter, because you can put
                 #anything in here and it still doesn't work
html_file_path = os.getcwd() + "\\data\\myfile.html"
if os.path.isfile(html_file_path):
    print("File exists!")
    actual_file = open(html_file_path, "a")
    actual_file.write(main_area_text)
else:
    print("File does not exist!")
    actual_file = open(html_file_path, "w")
    actual_file.write(main_area_text)

Earlier, in it's working state, I could create/write/append to .html and .txt files.

NOTE: If the file doesn't exist, the program still creates a new file... It's just empty.

I'm somewhat new to the python language, so I realize it's very possible that I could be overlooking something simple. (It's actually why I'm writing this code, to just familiarize myself with python.)

Thanks in advance!

Upvotes: 0

Views: 226

Answers (1)

howinator
howinator

Reputation: 56

Since you're not closing your file, the data isn't being flushed to disk. Instead try this:

main_area_text = "stuff"
html_file_path = os.getcwd() + "\\data\\myfile.html"
if os.path.isfile(html_file_path):
    print("File exists!")
    with open(html_file_path, "a") as f:
        f.write(main_area_text)
else:
    print("File does not exist!")
    with open(html_file_path, "w") as f:
        f.write(main_area_text)

The python with statement will handle flushing the data to disk and closing the data automatically. It's generally good practice to use with when handling files.

Upvotes: 4

Related Questions