how to add the selected files from dialog window to a dictionary?(如何将对话框窗口中的选定文件添加到字典中?)
问题描述
我希望它能够打开一个对话窗口并选择我的文件,
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}
我在网站上搜索过
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)
现在 myDict 是
Now the myDict is
myDict = {'C:/a.txt': 0}
myDict = {'C:/a.txt': 0, 'C:/b.txt': 1}
网上搜索后,添加os.path.split
After searching online, just add os.path.split
myDict = {}
for filename in filez:
head, tail = os.path.split(str(filename))
myDict[tail] = len(myDict)
现在一切正常
myDict = {'a.txt': 0, 'b.txt': 1}
我得到了没有路径的 myDict,问题解决了!谢谢!
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)
这篇关于如何将对话框窗口中的选定文件添加到字典中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将对话框窗口中的选定文件添加到字典中?
基础教程推荐
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
