[英]Retrieve multiple files from same directory
我正在創建一個具有25個按鈕的GUI程序,每個程序都訪問同一個文件夾中的唯一文件,我知道我可以對每個文件進行單獨編程以進入每個文件,但這似乎比需要的代碼多得多。有更有效的方法嗎? 這是代碼:
box1 = 'C:/Users/Geekman2/Documents/Tests/box1.txt
cupcake = Button(donut,text = "Box #1", command = open(box1))
這樣我就必須為每個文件創建一個變量,效率不是很高
PS:如果您感到困惑,我將所有變量命名為糕點
我會嘗試類似的代碼片段:
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))
對於要在頂部拒絕directory
和extension
變量的人來說,它使代碼可重復用於其他目錄和擴展,而無需創建新功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.