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

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

提问人:Jhonatta Silva 提问时间:1/2/2023 更新时间:1/2/2023 访问量:862

问:

我想等待文件卸载,我想在文件不存在时检查文件夹,我会放一个时间,直到文件完成下载。问题是我想检查文件是否存在,从名为“final_name”的子字符串变量开始,以“.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)
字符串 while-loop python-os

评论

0赞 wwii 1/2/2023
Could someone help me?- 您需要哪一部分的帮助?
0赞 wwii 1/2/2023
https://docs.python.org/3/library/glob.html,https://docs.python.org/3/library/pathlib.html#pathlib.Path.glob

答:

1赞 Cydog 1/2/2023 #1

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

法典:

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"))

评论

0赞 Jhonatta Silva 1/2/2023
但是这个函数会等到文件创建完毕吗?
0赞 Cydog 1/2/2023
@JhonattaSilva您可以使用此函数而不是在示例中使用此函数,那么它将等到创建文件。os.path.exists()