繁体   English   中英

如何检查文件是否存在于以 substring 开头并以 substring 结尾的文件夹中 Python

[英]How to check if a file exists in a folder starting with a substring and ending with a substring in Python

我想等待文件下载,我想在文件不存在时检查文件夹我会花时间直到文件完成下载。 问题是我想检查文件是否存在,以名为“final_name”的 substring 变量开头并以“.csv”结尾。 有人可以帮我吗?

    final_name = name.replace(" ", "").replace('(', '').replace(')', '').replace('-', '')\
        .replace('/', '').replace(r"'", '')

    print(final_name)

    time.sleep(5)

    while not os.path.exists(final_name):
        time.sleep(1)

您可以使用此 function 来检查文件是否存在。 它列出目录中的所有文件并循环遍历它们并检查文件是否以指定的字符串开头和结尾。

代码:

import os

def path_exists(directory, start, end):
    files = os.listdir(directory)
    for file in files:
        if file.startswith(start) and file.endswith(end):
            return True
    return False

# "./" is the current directory.
print(path_exists("./", final_name, ".csv"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM