在python中不保存外部文件的Append

2024-09-28 01:32:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何确保当我运行一个新的dict条目时,它确实保存了。在上次异常之前,当您“打印(辞典3[firstLetter]),它显示了新的附加dict条目,但实际上并没有保存在名为dictio的外部文件中。你知道吗

主要内容如下:

import fileinput
import dictio
from dictio import fullDict3

while True:
    try:
        srcTxt = input("Input word you want to look up: ")
        firstLetter = srcTxt[0]
        print(dictio.fullDict3[firstLetter][srcTxt])
    except: 
        try:
                queryInput = input('What does '+srcTxt+' mean?: ')       
                with open("C:\\Users...\\dictio.py", "a"):                 
                    dictio.fullDict3[firstLetter].update({srcTxt:queryInput})
                    print(dictio.fullDict3[firstLetter])                              
        except:
                    print("error has occured.")

以下是名为辞典这是一本字典:

fullDict3 = {
    '0':{
        '0data':'0datttaaa',
        '0mada':'0mmmaadaa'
    },
    'a':{
        'arbre':'tree',
        'arc-en-ciel':'rainbow'
    },
    'b':{
        'bierre':'beer',
        'belle':'beautiful'       
    }
}

Tags: 文件import内容input条目dictprinttry
2条回答

好吧。没有太多时间编写代码,但在阅读并尝试一个错误后,终于解决了我的问题,但是对于任何遇到此问题的人来说,都可以轻松找到一种更干净、更有效的方法来完成:

while True:
    try:
        srcTxt = input("Input word you want to look up: ")
        firstLetter = srcTxt[0]
        if srcTxt == "ESC":
            break
        print(dictio.fullDict3[firstLetter][srcTxt])
    except: 
        try:
            queryInput = input('What does '+srcTxt+' mean?: ')
            with open('C:\\Users...\\dictio.py', 'r') as f:
                fullDict3[firstLetter].update({srcTxt:queryInput})
                newDict = "fullDict3 = "+json.dumps(fullDict3)
            with open('C:\\Users...\\dictio.py', 'w') as f:
                f.write(newDict)
                f.close()
        except:
            print("error has occured.")

不能通过导入操作模块的内容来更改模块的内容。没有理由导入fullDict3。相反,将起始结构存储在fullDict3.json。通过返回可以更改的dict的json.load将该文件转换为Python对象。当更新的dict准备好写入磁盘时,通过json.dump保存它。你知道吗

相关问题 更多 >

    热门问题