如何将对话框窗口中的选定文件添加到字典中?

2023-06-05Python开发问题
2

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

问题描述

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

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)

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

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11