how to add the selected files from dialog window to a dictionary?

时光毁灭记忆、已成空白 提交于 2019-12-30 12:04:28

问题


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!


回答1:


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)


来源:https://stackoverflow.com/questions/17580764/how-to-add-the-selected-files-from-dialog-window-to-a-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!