Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将字典写入.py文件?_Python_Dictionary_Permission Denied - Fatal编程技术网

Python 如何将字典写入.py文件?

Python 如何将字典写入.py文件?,python,dictionary,permission-denied,Python,Dictionary,Permission Denied,我在“albums_data.py”和“album.py”中有一个字典作为主程序。 我需要更新主程序中的add_one()函数,将字典的实际状态写入“albums_data.py”,并在一些数据添加到字典后保存它(使用add_one()函数) 以下是源代码: 相册_data.py albums= {} albums["Adele"]="21" albums["Michael Jackson"]="Thriler" albums["Lady Gaga"]="The Fame" 相册.py imp

我在“albums_data.py”和“album.py”中有一个字典作为主程序。 我需要更新主程序中的
add_one()
函数,将字典的实际状态写入“albums_data.py”,并在一些数据添加到字典后保存它(使用
add_one()
函数)

以下是源代码:

相册_data.py

albums= {}
albums["Adele"]="21"
albums["Michael Jackson"]="Thriler"
albums["Lady Gaga"]="The Fame"
相册.py

import tkinter
from albums_data import *

root=tkinter.Tk()
root.title("DICT example")

#Functions
def show_all():
    #clear the listbox
    lb_music.delete(0,"end")
    #iterate throught the keys and add to the listbox
    for artist in albums:
        lb_music.insert("end",artist)

def show_one():
    artist=lb_music.get("active")    #active is clicked field
    album=albums[artist]
    msg=artist+" - "+album
    lbl_output["text"]=msg  #Ready is replaced with msg

def add_one():
    info=txt_input.get()
    split_info=info.split(",") #list is created after is separated with ","
    artist=split_info[0]
    album=split_info[1]
    albums[artist]=album
    show_all()
    txt_input.delete(0,"end")

    #write to .py file (not worked to txt also) ->permission denied
    f = open("albums_data.py","w")
    f.write( str(albums) )
    f.close()


#GUI
lbl_output=tkinter.Label(root,text="Ready")
lbl_output.pack()

txt_input=tkinter.Entry(root)
txt_input.pack()

lb_music=tkinter.Listbox(root)
lb_music.pack()

btn_show_all=tkinter.Button(root,text="Show all",command=show_all)
btn_show_all.pack()

btn_show_one=tkinter.Button(root,text="Show one",command=show_one)
btn_show_one.pack()

btn_add_one=tkinter.Button(root,text="Add one",command=add_one)
btn_add_one.pack()


root.mainloop()
使用


你需要问一个明确的问题。这是一个非常糟糕的主意。改为使用。为什么要使用string方法而不是普通的
dump
load
?@Novel,因为我忘了它们。:)谢谢你的建议。我试图调查……这对我来说都是新鲜事:)
import json

d = { "hello": "world" }

with open('state.json', 'w') as f:
    json.dump(d, f)

with open('state.json', 'r') as f:
    d2 = json.load(f)

assert d == d2