Forums

Writing to file not working

I have a function that is meant to add some data to a file. Basically, it writes appends the data to the file and then reads it back into a dictionary stored in the class as self.dicts.

 path = os.path.join(my_dir, 'filename.txt')
 def add(self, key, value, type):
    """Key is just the dictionary key. Same with value. Type could be something like "comment" or "post" or
    something """
    if len(str(self.dicts)) > 4: #this fixes some errors for whatever reason.
        text = ', "' + type + key + '"' + " : " + '"' + value + '"'
    else:
        text = '"' + type + key + '"' + " : " + '"' + value + '"'
    with open(path + ".txt", "a") as f:
        f.write(text)
    with open(path + ".txt", "r") as f:
        self.dicts = ast.literal_eval("{" + f.read() + "}")

As far as I can tell no errors are happening but the file remains stubbornly empty.

Write to support@pythonanywhere.com with more context and more specific examples.