【发布时间】:2018-04-25 15:34:06
【问题描述】:
我正在用 Tkinter 编写一个界面,我想自动执行一项任务。实际功能打开一个允许用户选择文件的窗口(我指定文件的类型。然后从其他功能中检索这些文件的路径以修改文件。这是我的实际功能:
def get_path(): #return the path of the selected file(s)
root = Tk()
i= datetime.datetime.now()
day = i.day
month=i.month
root.filename = filedialog.askopenfilenames(initialdir = "Z:\SGI\SYNCBBG",title = "Select your files",filetypes = (("Fichier 1","f6365full_account_refresh*"+str(month)+str(day)+".1"),("Fichier 1","f6365icsh*"+str(month)+str(day)+".1"),("all files",".*")))
root.withdraw()
return (root.filename)
我想要的只是有一个函数可以自动检索两个不同目录中的所有类型(我指定)的文件。我这样做了,代码运行并打印了结果,但是在那之后 Python 停止响应并且出现了一个错误,所以我必须关闭 Python。另一件事是我得到的是文件名,而不是绝对路径,但这不是主要问题:
def path_L2():
os.chdir("Z:/SGI/SYNCBBG/L2/results/results")
for file in glob.glob("f6365full_account_refresh*"+str(month)+str(day)+".1"):
return file
for file in glob.glob("f6365icsh*"+str(month)+str(day)+".1"):
return file
def path_L3():
os.chdir("Z:/SGI/SYNCBBG/L3/results/results")
for file in glob.glob("f6365full_account_refresh*"+str(month)+str(day)+".1"):
return file
for file in glob.glob("f6365icsh*"+str(month)+str(day)+".1"):
return file
paths=path_L2()
print(paths)
【问题讨论】:
-
您应该仔细考虑
return语句在函数中的作用... -
您的函数只返回找到的第一个文件,而不是文件列表。另外,最好不要
chdir(这对整个过程来说是全局的)。使用os.path.join将路径添加到全局字符串,您将从当前目录获得文件的可用路径。 -
我在这里看不到任何会导致程序挂起的东西。开始在代码中的循环中添加打印语句,看看是否永远运行。
标签: python-3.x file tkinter chdir