add items to a dictionary and save it to a txt file
Question: a few weeks ago i have started learning python.

Now i have started to create a program to create a dictionary, add an item1 as
a string, add an item2 wich consists of numbers and save it after that. But it
is not working the way i want it to. It seems like the saving is not working
properly it seems to be overwriting the existing items.

Before posting this, i have thoroughly searched here on Stackoverflow to find
a solution, but i cant get it to work.

Here is my code:

    
    
    import pickle
    import os
    
    
    if not os.path.exists( 'C:\path' ):  
        os.makedirs( 'C:\path' )        
    
    dict = {}
    dict = pickle.load( open( "dict.txt", "rb" ) )
    
    def add_dict(item):
    
        for item in dict:
    
            if not item in dict:
                dict.update({item1 : item2})
                print ("thx")
                print (dict)
                print ("added")
    
            if item in dict:
                print("item already exists.")
    
            return
    
        return
    
    
    
    item1 = input("insert Item1: ")
    item1 = item1.lower()
    item2 = input("insert item2: ")
    
    
    pickle.dump(dict, open("C:\path\dict.txt", "wb"))
    

I hope this is not a too specific case.

edit: I have edited my code, to make it less specific and made two mistakes
which are fixed now.

    
    
    import pickle
    import os
    
    if not os.path.exists( 'C:\path' ):
        os.makedirs( 'C:\path' )
    
    dict = {}
    item1 = input('insert item1 ')
    item1 = buch.lower()
    item2 = input('insert item2: ')
    dict.update({item1: item2})
    print("thx")
    print(dict)
    print("added")
    pickle.dump(dict, open("C:\path\dict.txt", "wb"))
    

this was the code without the function.


Answer: The edited code still has errors.

I rewrote the whole thing to be more pythonic.

    
    
    import os
    import pickle
    
    
    def read_data(filename):
        try:
            return pickle.load(open(filename, 'rb'))
        except FileNotFoundError:
            return {}
    
    
    def write_data(filename, data):
        try:
            os.makedirs(os.path.dirname(filename))
        except FileExistsError:
            pass
        pickle.dump(data, open(filename, 'wb'))
    
    
    def main():
        filename = os.path.join(os.path.dirname(__file__), 'dict.txt')
        data = read_data(filename)
    
        key = input('insert item1 ').lower()
        value = input('insert item2: ')
        data[key] = value
        print(data)
    
        write_data(filename, data)
    
    
    if __name__ == '__main__':
        main()
    

I used meaningful names and didn't call a variable `dict` because
[dict](https://docs.python.org/3/library/functions.html#func-dict) is a
builtin you don't want to overwrite.

First we read the file. If it doesn't exist we catch the error and use an
empty dictionary for the data.

Second we get the new data and update the dictionary.

Last we write the dictionary back to disk and create the target folder if it
doesn't exist.

