簡體   English   中英

使用 python 檢查文件夾中是否存在特定文件

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

我想檢查特定文件夾中是否存在文件並打印 output。 我在路徑中有以下文件: ./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中。 output 應該如下:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM