[英]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.