Python 2.7 检查是否存在指定文件名的文件

Python 2.7 check if there is a file with a specific file name

我想检查文件夹中是否有名称包含特定字符串的文件,例如:

文件夹:

-- hi.txt

-- bye.txt

-- bedanagain.txt

-- dan1.txt

-- dan2.txt

-- gray.txt

return 如果文件夹中有名称中包含 "dan" 的文件,则为真。

另外,如果可能,我需要使用最知名的导入(客户对使用不知名的开源包感到紧张)和最少数量的导入。

我尝试使用 os.path.exists,但我发现它只有在您拥有完整文件名时才有效,而且它无法搜索包含某些字符串的文件名。

我试过了:

import os
print os.path.exists('./dan') // false
print os.path.exists('./dan*') // false
print os.path.exists('./*dan') // false

这也是为什么这不是重复的原因 - 我检查了提到的提要,它涉及 "if a file exists" 而不是 "if a file with some string in its name exists"

谢谢!

如果您正在使用 mac,请尝试查看 'os' 模块(它应该内置在您的计算机中),您可以使用以下方式导入它:

import os

您可以 运行 shell 从 python 中使用

命令
os.system("your command")

例如

os.system("echo "This is terminal"")

我确定有一个终端命令可以让您检查文件夹中的特定文件。

您可以使用 os.listdir("dir path") 获取列表目录中的所有文件并检查该列表中的文件名:

import os
def check_file():
    x = os.listdir("path to dir")
    for i in x:
        if ["hi","bye","bedanagain","dan1","dan2","gray"] in i:
            return True

您可以使用 OS 模块。

例如:

import os
for file in os.listdir(Path):
    if "dan" in file:
        print(file)