python - 从同一目录检索多个文件

标签 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))

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

附注如果您感到困惑,我以糕点命名所有变量

最佳答案

我会尝试类似这样的代码片段:

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变量投反对票的人,它使代码可重用于其他目录和扩展,而无需创建一个新函数。

关于python - 从同一目录检索多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12922693/

相关文章:

python - 在 PyDev/Eclipse 中使用适当的类浏览器是否有更好的方法来探索 Python 标准库?

asp.net - 以 kwargs 为单位的动态值

python - 用python检测英文文本

python - 检测应用层协议(protocol),python?

android - 如何在 kotlin android 中共享 .txt 文件

java - 如何将这样的文件插入 MySQL 数据库

python - 使用 configparser 写入文件时定义 config.ini 条目的顺序?

Python 数组旋转

python - 如何构建不区分大小写的枚举?

r - 使用 R 获取文本文件中的行数