Python 3.5 Tkinter如何将dict保存到文件中

时间:2017-01-06 10:13:15

标签: python python-3.x dictionary tkinter

所以我的问题是我运行程序一旦完成基本功能就出现一个弹出框询问用户是否要保存文件,如果'是'则会出现一个保存对话框。因为我正在保存的数据是一个字典值,我收到了来自tkinter的错误。我试图使用“.csv”扩展名作为保存点,因为我读到某个地方可以将dict保存到它们中,但我要么采用这种错误方式,要么我的代码中存在问题。

更新了代码并解释了原因

原始代码片段:

def flag_detection():

total_count = Counter(traffic_light)
total_count.keys()
for key, value in total_count.items():

    EWT = tkinter.messagebox.askquestion('File Level', 'Would you like to save')

    file_opt = options = {}
    options['filetypes'] = [('all files', '.*'), ('text files', '.csv')]
    options['initialfile'] = 'myfile.csv'

    if EWT == 'yes':
        savename = asksaveasfile(file_opt, defaultextension=".csv")
        savename.write(key, ':', value)

错误讯息:

    Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Lewis Collins\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1550, in __call__
    return self.func(*args)
  File "C:/Users/Lewis Collins/PycharmProjects/program_06.01.17/Home.py", line 108, in run_language_model
    main.flag_detection()
  File "C:\Users\Lewis Collins\PycharmProjects\program_06.01.17\main_code\main.py", line 179, in flag_detection
    savename = asksaveasfile(file_opt, defaultextension=".csv")
  File "C:\Users\Lewis Collins\AppData\Local\Programs\Python\Python35-32\lib\tkinter\filedialog.py", line 423, in asksaveasfile
    return open(filename, mode)
TypeError: open() argument 2 must be str, not dict

由于Tkinter抛回它无法将dict保存到文件中我尝试了下面的将dict转换为str的解决方案,这也导致了问题

函数的代码片段尝试转换为str for tkinter:

def flag_detection():


total_count = Counter(traffic_light)
total_count.keys()
for key, value in str(total_count.items()):
    EWT = tkinter.messagebox.askquestion('File Level', 'Would you like to save')
    file_opt = options = {}
    options['filetypes'] = [('all files', '.*'), ('text files', '.csv')]
    options['initialfile'] = 'myfile.csv'

    if EWT == 'yes':
        savename = asksaveasfile(file_opt, defaultextension=".csv")
        savename.write(key, ':', value)

所以我更新了我的代码,尝试使用str(total_count.items()):转换为dict,因为我在阅读它们之后并不完全理解json和pickle库它们似乎很复杂,因为我需要的是简单输出到文件,供用户进行查看。

我现在收到此错误:

    Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Lewis Collins\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1550, in __call__
    return self.func(*args)
  File "C:/Users/Lewis Collins/PycharmProjects/program_05.0.17/Home.py", line 108, in run_language_model
    main.flag_detection()
  File "C:\Users\Lewis Collins\PycharmProjects\program_05.0.17\main_code\main.py", line 169, in flag_detection
    for key, value in str(total_count.items()):
ValueError: not enough values to unpack (expected 2, got 1)

欢迎任何建议或反馈,提前致谢。

1 个答案:

答案 0 :(得分:2)

第一个问题是这一行:

savename = asksaveasfile(file_opt, defaultextension=".csv")

根本不是如何调用asksaveasfileasksaveasfile没有将字典作为其第一个参数。如果要使用file_opt1中的选项:

,您应该这样调用它
savename = asksaveasfile(defaultextension=".csv", **file_opt)

当您解决这个问题时,下一个问题是您尝试使用此语句编写的内容:

savename.write(key, ':', value)

您收到以下错误消息:TypeError: write() takes exactly 1 argument (3 given)。它完全意味着它所说的:你需要提供一个参数而不是三个参数。你可以通过给write正好一个参数来解决这个问题:

savename.write("%s: %s" % (key, value))

但是,如果您只想将字典保存到文件中,json模块就可以轻松实现这一点,而无需迭代值。

要另存为json,请将flag_detection方法更改为:

import json
...
def flag_detection():

    total_count = Counter(traffic_light)

    EWT = tkinter.messagebox.askquestion('File Level', 'Would you like to save')

    file_opt = options = {}
    options['filetypes'] = [('all files', '.*'), ('text files', '.json')]
    options['initialfile'] = 'myfile.json'

    if EWT == 'yes':
        savefile = asksaveasfile(defaultextension=".json", **file_opt)
        json.dump(total_count, savefile)

如果您想保存为csv文件,请阅读DictWriter类的文档,该文档以类似的方式工作。