簡體   English   中英

我如何向 python 中的字典添加內容,該內容存在於另一個 python 文件的另一個文件中

[英]how can i add something to a dictionary in python which is present in another file from another python file

我正在嘗試以 python 字典的形式獲取聯系人,該字典存在於名為“phone.py”的文件中,我想從另一個名為“test.py”的文件中的另一個 function 添加聯系人到該字典'.

電話.py

phone_numbers={
'john': '+91123456789',
'berry': '+91987654321',
}

測試.py

import phone.py

def add_contact():

    name_contact = input("what is the name :")
    phone_contact = input("contact number")
    file = open("phone.py", "a", encoding='utf-8')
    file.truncate()
    file.write("'"+name_contact+"'" + ':'+"'+91"+phone_contact+"'"+",")
    file.close()
add_contact()

我目前得到的結果。

電話.py

phone_numbers={
'john': '+91123456789',
'berry': '+91987654321',
}'jerry': '+916543217890',

我想要它是什么。

電話.py

phone_numbers={
'john': '+91123456789',
'berry': '+91987654321',
'jerry': '+916543217890',
}

您的文件包含文本內容。 您可以使用以下方法向文件中添加行

def add_contact():
    name_contact, phone_contact = read_param()
    lines = None
    with open('phone.py') as input_file:
        lines = input_file.readlines()
        lines[-1:] = "'{0}':'+91{1}',{2}".format(name_contact, phone_contact, '\r')
        lines.append("}")
    with open("phone.py", 'w') as output_file:
        output_file.writelines(lines)
        output_file.close()

def read_param():
    name_contact = input("what is the name :")
    phone_contact = input("contact number :")
    return name_contact, phone_contact

但是最好保持數據為json格式或者更簡單(不是dict的形式而是每行一個聯系人)

例如

  1. 像這樣的簡單記錄 "john": "+91123456789" "berry": "+91987654321"。 . .

只是 append 換行

def append_line():
    with open('phone.py', 'a') as input_file:
        name_contact, phone_contact = read_param()
        input_file.writelines("'{0}':'+91{1}'".format(name_contact, phone_contact))
  1. json

你的文件內容是這樣的

{
"john": "+91123456789",
"berry": "+91987654321"
}

並使用以下代碼

def add_contact_json():
    with open('phone.py') as json_file:
        data = json.load(json_file)
        name_contact, phone_contact = read_param()
        data[name_contact] = "'+91{0}".format(phone_contact)

    with open('phone.py', 'w') as json_file:
        json.dump(data, json_file)

暫無
暫無

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

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