简体   繁体   中英

How to update a dictionary in a file with Python?

I'm trying to get a dictionary from a file, add some data to it and save it back to the same file. When I run the program, it always goes to except after it prints 1 and loops like that forever. How can I fix it?

This is the data I pass to the function(this is sample data - I actually pass a password and an username encrypted with a random key): key: '␙⋉∡' value: ['␙⋉∡➵ᾁ῕ᾁ', 84, None]} file_name: 'database.database'

This is the error:

Traceback (most recent call last):
  File "C:\Users\HP\Currently_Working_On\Database_Login_Chat.py", line 46, in write_data
    file_data = eval(file_data)
  File "<string>", line 0
    
SyntaxError: unexpected EOF while parsing

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\HP\Currently_Working_On\Database_Login_Chat.py", line 52, in write_data
    file2.write(str(file_data))
  File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 2-3: character maps to <undefined>
def write_data(key, value, file_name):
    try:
        file = open(file_name, "r")
        file_data = str(file.read())
        file.close()

        file_data = eval(file_data)
        file_data[key] = value

        file_data = str(file_data)
        file2 = open(file_name, "w")
        print("1")
        file2.write(str(file_data))
        print("2")
        file2.close()
        print("3")
    except:
        file3 = open(file_name, "w")
        file3.write("{}")
        file3.close()
        print("0")
        write_data(key, value, file_name)

To pass thru encoding error try to specify encoding parameter to all read and write parts of your code like this:

...
file = open(file_name, "r", encoding='utf-8')
...
file2 = open(file_name, "w", encoding='utf-8')
...
file3 = open(file_name, "w", encoding='utf-8')
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM