简体   繁体   English

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

[英]Check if a particular file is present in the folder using python

I would like to check if a file is present in a particular folder and print the output.我想检查特定文件夹中是否存在文件并打印 output。 I have the following files in the path: ./programs/data/my_files :我在路径中有以下文件: ./programs/data/my_files

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

I would like to check if the files data.txt, filename.txt, and an_55.txt is present in the path ./programs/data/my_files .我想检查文件data.txt, filename.txt, and an_55.txt是否存在于路径./programs/data/my_files中。 The output should be the following: output 应该如下:

Success: data.txt exists 

What I tried so far?到目前为止我尝试了什么?

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

This prints success only for the last item in the list, (i,e, an_55.txt), others are failure.这仅对列表中的最后一项(即 an_55.txt)打印成功,其他项为失败。 How do I correct this?我该如何纠正?

Try this尝试这个

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

You can also use os.path.exists("path to a file")你也可以使用os.path.exists("path to a file")

This might be helpful这可能会有所帮助

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

暂无
暂无

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

相关问题 如何使用python检查CSV文件的特定列中是否存在列表中的字符串? - How to check if a string in a list is present in a particular column in a CSV file using python? 如何使用 lambda、boto3 和 python 2.7 检查 s3 的顶级文件夹中是否存在特定文件 - How to check if a particular file exists in a top level folder in s3, using lambda, boto3 and python 2.7 将文件下载到特定文件夹 python - Download a file to a particular folder python 使用python中的URL和文件路径将csv导出到特定文件夹 - Export csv to a particular folder using URL & file path in python 如何使用 Python 在 google colab 的特定文件夹中写入文件? - How to write a file on a particular folder on google colab using Python? 如何在 python 中使用 openpyxl 将 excel 文件保存在特定文件夹中 - How to save an excel file in a particular folder using openpyxl in python 如何使用Python检查CSV文件中是否已存在数据 - How to check if an data already present in a CSV file using Python 如何检查python中的文件夹中是否存在.dat文件,如果存在,如何将其与关联的csv匹配? - How to check if a .dat file is present in a folder in python and if it is there,how to match it with associated csv? python显示文件夹中不存在的excel文件 - python is showing a excel file that is not present in a folder 如何在python中检查文件夹中的特定文件或目录并根据某些条件移动它 - How to check for a particular file or directory in a folder and move it bases on certain criteria, in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM