如何将所选文件从对话窗口添加到字典? [英] how to add the selected files from dialog window to a dictionary?

查看:122
本文介绍了如何将所选文件从对话窗口添加到字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够打开一个对话窗口并选择我的文件,

  a.txt 
b。 txt

然后将其添加到我的字典中

  myDict = {a.txt:0,
b.txt:1}

我在网站上搜索

  import Tkinter,tkFileDialog 
root = Tkinter.Tk()
filez = tkFileDialog.askopenfilenames(parent = root,multiple ='multiple',title ='选择一个文件')

这些代码用于打开对话窗口并选择我的文件。
但问题是如何将所选文件添加到字典?



与Stephan的答案一起,问题解决了



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $$ en + str(myDict)

现在myDict是

  myDict = {'C:/a.txt':0} 
myDict = {'C:/a.txt':0,'C:/ b。 txt':1}

在网上搜索后,只需添加os.path.split

  myDict = {} 
在filez中的文件名:
head,tail = os.path.split(str(filename) )
myDict [tail] = len(myDict)

现在一切正确

  myDict = {'a.txt':0,'b.txt':1} 

我的myDict没有路径,问题解决了!
谢谢!

解决方案

  myDict = {} 
myDict [ filenameFromDialog] = len(myDict)

这是添加到字典的语法。

如果您有要添加到字典的文件数组,您可以循环遍历列表,并一次添加一个:

  myDict = {} 
在filez中的文件名:
myDict [filename] = len(myDict)


I wish it's able to open a dialog window and select my files,

a.txt
b.txt

then add them in my dictionary

myDict = { "a.txt" : 0,
           "b.txt" : 1}

I searched on website

import Tkinter,tkFileDialog
root = Tkinter.Tk()
filez = tkFileDialog.askopenfilenames(parent=root,multiple='multiple',title='Choose a file')

these codes work for opening a dialog window and selecting my files. But the question is how to add the selected files to the dictionary?

With Stephan's answer, the problem is solved

myDict = {}
for filename in filez:
    myDict[filename] = len(myDict)
    print "myDict: " + str(myDict)

Now the myDict is

myDict = {'C:/a.txt': 0}
myDict = {'C:/a.txt': 0, 'C:/b.txt': 1}

After searching online, just add os.path.split

myDict = {}
for filename in filez:
    head, tail = os.path.split(str(filename))
    myDict[tail] = len(myDict)

Now everything is right

myDict = {'a.txt': 0, 'b.txt': 1}

I got the myDict without path, problem solved! Thanks!

解决方案

myDict = {}
myDict[filenameFromDialog] = len(myDict)

That is the syntax for adding to a dictionary.

If you have an array of files you want to add to the dictionary, you could loop over the list and add them one at a time:

myDict = {}
for filename in filez:
    myDict[filename] = len(myDict)

这篇关于如何将所选文件从对话窗口添加到字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆