0

I am trying to find if a given file pattern is available in a directory. If found, I would want to open and load as JSON. If not found, I would like to send an email saying that the file is not present.

File name: test_09082021.txt

import os

path ='/dev/stage/'
file_pattern = 'test*'

file = path + file_pattern

if os.path.isfile(file):
   with open(file) as f:
      data = json.load(f)
else:
   mailserver.sendmail('abc@gmail.com','def@gmail.com',msg.as_string())

But the application couldn't find the file and is returning false in the IF statement.

Could you please advise how I can check for the file pattern to make this work?

vvazza
  • 421
  • 7
  • 21

2 Answers2

1

Your code doesn't work because it checks if a file with the given name "test*" exist - that's not the same as creating a list of all files that have a pattern.

Have a look at the following for an example of using file patterns: Find all files in a directory with extension .txt in Python

Ingo Wald
  • 90
  • 4
1

I would use glob library:

import glob
import json

path ='/dev/stage/'
file_pattern = 'test*'

pattern = path + file_pattern
matched_files = glob.glob(pathname=pattern)
try:
   with open(matched_files[0]) as f:
      data = json.load(f)
except IndexError:
    mailserver.sendmail('abc@gmail.com','def@gmail.com',msg.as_string())

Use try, except block, according to python ask forgiveness not permission principle.

glob() returns list of files, which matched the desired pattern. If there is no file, python will throw IndexError and you send email. Otherwise first file is opened as json.

Peter Trcka
  • 1,279
  • 1
  • 16
  • 21