微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用python检查文件夹中是否存在特定文件

如何解决使用python检查文件夹中是否存在特定文件

我想检查特定文件夹中是否存在文件并打印输出。我在路径中有以下文件./programs/data/my_files:

data.txt
an_123.txt
info.log
an_234.txt
filename.txt
main.py
an_55.txt

我想检查文件 data.txt,filename.txt,and an_55.txt 是否存在于路径 ./programs/data/my_files 中。输出应如下所示:

Success: data.txt exists 

到目前为止我尝试了什么?

pth = str("./programs/data/my_files/")
filename = ['data.txt','filename.txt','an_55.txt']

for i in filename:
    if glob.glob(os.path.join(pth)):
       print('Success: ',"NaN_"+i+".xml exists")
    else:
       print('Failure: ',"NaN_"+i+".xml does not exists")

这仅对列表中的最后一项打印成功,(即 an_55.txt),其他为失败。我该如何纠正?

解决方法

试试这个

import os
files = os.listdir("your/path/to/files")
for file in files:
      if file.startswith("data") # you can also check if the item is a file here os.isfile()
            print("success")

您也可以使用 os.path.exists("path to a file")

,

这可能会有所帮助

from pathlib import Path

my_file = Path("/path/to/file") #add your path lists 

if my_file.is_file():
      print("present")
else:
      print("not present")

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。