简体   繁体   中英

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. I have the following files in the path: ./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 . The output should be the following:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM