0

I'm trying to write some text directly into a python file that I intend to store data in a dictionary. The script runs and works perfectly and writes the data I need into a key-value pair within the dictionary of the file. However when the script finishes and I check the file, at the very top of the file I get a string of diamond shapes with a question mark in them.

This is the code:

def add_new_value(key, var):
        total = ",'"+key+"'"+":"+var+" #$%$#"
        print(total)
       
        with open("TheseusDictionary.py","r+", encoding = "utf-8") as  intent:
             read=intent.read()
             with open("TheseusDictionary.py", "w+", encoding = "utf-8") as far:
                 print("second phase complete")
             print(read)
             read = read.replace("#$%$#",total)
        
             intent.write(read)
             

add_new_value("False", "1")

#$%$# is a comment within my dictionary file that I use to tell at what point in the file to insert the key-value pair. What's causing these characters at the top of the file?

  • 1
    I don't have a great feeling about that second open of TheseusDictionary. Note as well the warning in the top answer here: https://stackoverflow.com/questions/14271216/beginner-python-reading-and-writing-to-the-same-file – JonSG Feb 07 '23 at 19:45
  • 2
    Junk at the top of a file screams BOM. Although I couldn't tell where it should come from. Some editors (I'm looking at you, notepad!) insert them for fun to break files and confuse users. – Friedrich Feb 07 '23 at 19:50
  • 1
    With `intent`, you read the entire file, and then write new data starting at the current file position - which is at the *end* of the data you just read. But in the meantime, you opened `far` for writing, which cleared the contents of the file. So your new data ended up written after a gap, equal in size to the original data; the garbage you're seeing is the null characters that implicitly fill that gap. – jasonharper Feb 07 '23 at 20:13
  • _write some text directly into a python file that **I intend to store data in a dictionary**_ - this is really bad idea, there are plenty of better options. Almost everything else would be better. And the way you implement it makes it even worse. – buran Feb 07 '23 at 20:27

0 Answers0