问题描述
我想检查特定文件夹中是否存在文件并打印输出。我在路径中有以下文件:./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")