【问题标题】:Automate selection of files with Python使用 Python 自动选择文件
【发布时间】: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


【解决方案1】:

return 将立即从函数返回。在您的情况下,您将在每个函数中返回第一个 glob 语句的第一个结果,然后退出该函数。

您要做的就是获取从glob 返回的列表并将它们加在一起。你想要这样的东西:

def path_L2():
    os.chdir("Z:/SGI/SYNCBBG/L2/results/results")
    return glob.glob("f6365full_account_refresh*"+str(month)+str(day)+".1") + glob.glob("f6365icsh*"+str(month)+str(day)+".1")

def path_L3():
    os.chdir("Z:/SGI/SYNCBBG/L3/results/results")
    return glob.glob("f6365full_account_refresh*"+str(month)+str(day)+".1") + glob("f6365icsh*"+str(month)+str(day)+".1")

不过,我不会使用 os.chdir - 它会主动更改您的工作目录。此外,由于除了一个字符串之外,您的两个函数是等效的,因此您应该创建一个函数来完成所有这些工作。 (使用函数的目的是不必一遍又一遍地重复相同的代码。)我会做以下事情。 (为了简洁起见,我添加了一些额外的变量。)

def path_L(l_dir):
    path1 = "f6365full_account_refresh*"+str(month)+str(day)+".1"
    path2 = "f6365icsh*"+str(month)+str(day)+".1"
    glob_expr1 = os.path.join(l_dir, path1)
    glob_expr2 = os.path.join(l_dir, path2)

    return glob.glob(glob_expr1) + glob.glob(glob_expr2)

然后您可以拨打path_L 获取L2:

l2_paths = path_L("Z:/SGI/SYNCBBG/L2/results/results")
l3_paths = path_L("Z:/SGI/SYNCBBG/L3/results/results")

【讨论】:

    猜你喜欢
    • 2010-12-19
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-24
    相关资源
    最近更新 更多