簡體   English   中英

如何在 python 上使用 dict 將鍵和值寫入文件?

[英]How to write key and value to file with dict in it on python?

我最近開始學習 python,我需要你們的幫助。

例如:我有一個名為Data.py的文件,其中有一個字典d={} ,我在其中添加鍵和值。

另外,我有一個名為Main.py的文件。 我想在字典中添加帶有值的鍵,保存它,然后嘗試在Main.py文件中打印它。 那可能嗎?

升級版:

我認為我最好使用 JSON,但另一個問題是如何使用 JSON 做到這一點? 我有 0 次使用 JSON 的經驗。 我需要以某種方式將字典放在那里,然后解析以獲取信息,添加鍵和值並保存文件。

您可以使用 json 文件,甚至可以使用帶有return語句的 function。

確保兩個文件都在同一個目錄(文件夾)中,並將Data.py重命名為get_data.py ,然后編寫一個新的 function。

def transfer():
    global d

    return d

d = {}

在您的Main.py中:

from get_data import *
print(transfer())

這是實現JSON文件的一種方法

#Data.py
import json

d = {'total': 0}
f = open('data.txt', 'w')
while True:
    x = input('Enter number: ')
    if x.lower() == 'q':
        f.close()
        break
    elif x.isdigit():
        d['total'] += float(x)
        f.seek(0, 0)
        f.write(json.dumps(d))

Output #Data.py

Enter number:  12
Enter number:  13
Enter number:  q

在另一個代碼中

#main.py

import json

f = open('data.txt', 'r').read()
d = json.loads(f)
print(d['total'])
f.close()

Output #Main.py

25.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM