从同一目录中检索多个文件

时间:2012-10-16 20:13:57

标签: python python-2.7 text-files

我正在创建一个有25个按钮的GUI程序,每个按钮访问同一个文件夹中的一个唯一文件,我知道我可以单独编写每个文件以转到每个文件,但这似乎比需要更多的代码是,有更有效的方法吗? 这是代码:

box1 = 'C:/Users/Geekman2/Documents/Tests/box1.txt
cupcake = Button(donut,text = "Box #1", command = open(box1))

这样做我必须为每个文件创建一个变量,效率不高

P.S。如果你感到困惑,我会在糕点

之后命名我的所有变量

1 个答案:

答案 0 :(得分:1)

我会尝试与此类似的代码段:

directory = 'C:/Users/Geekman2/Documents/Tests/'
...
def AddDirTo(filename)
     return directory + filename

然后您发布的代码将变为:

box1 = AddDirTo('box1.txt') #note: you did close box1's quote on your question
cupcake = Button(donut,text = "Box #1", command = open(box1))

如果你拥有的每个文件都是一个文本文件,正如问题所示,你甚至可以做到:

directory = 'C:/Users/Geekman2/Documents/Tests/'
extension = '.txt'
...
def AddDirTo(filename):
     return directory + filename + extension
...
box1 = AddDirTo('box1') #note: you did close box1's quote on your question
cupcake = Button(donut,text = "Box #1", command = open(box1))

对于那些想要对顶部的directoryextension变量进行投票的人,它使代码可以重用于其他目录和扩展,而无需创建新函数。

相关问题