-1

I am using Python 3 and want to check for 2 things. Firstly I want to ensure there are 3 files in a directory, then I want to check that the 3 files match certain rules....

  • 3 files in directory
  • A file called testfile1.txt
  • A file that matches myfile-*.txt (for example myfile-473spain.txt)
  • A file that matches newlog-*.log (for example newlog-55.log)

I have this so far...

list = os.listdir('myfiles') # dir is your directory path
number_files = len(list)

if number_files !=3 :
    print('Incorrect Number Of Files')
else:
    print('Correct Number Of Files')

if os.path.isfile('myfiles/testfile1.txt'):
    print ("myfiles/testfile1.txt - FOUND")
else:
    print ("myfiles/testfile1.txt - NOT FOUND")

But I am now stuck on how to search for the 2 partial match files. What can I try next?

halfer
  • 19,824
  • 17
  • 99
  • 186
fightstarr20
  • 11,682
  • 40
  • 154
  • 278
  • 2
    Does this answer your question? [Find files in a directory with a partial string match](https://stackoverflow.com/questions/37420624/find-files-in-a-directory-with-a-partial-string-match) – Georgy Apr 26 '20 at 23:32
  • 1
    _But I am now stuck on how to search for the 2 parital match files._ Can you be more specific about which pat you're struggling with? As an aside, I would recommend using pathlib instead of os for these kinds of tasks. – AMC Apr 27 '20 at 03:40

3 Answers3

1

Use glob.glob:

import glob

if glob.glob('myfiles/myfile-*.txt'):
    print('match for "myfile-*.txt" found')
else:
    print('match for "myfile-*.txt" not found')
jfaccioni
  • 7,099
  • 1
  • 9
  • 25
1

You could loop over the list you created in your first rule. Then you could you the "in" statement: Something like:

for fileName in list:
   if ("myfile-" in fileName and ".txt" in fileName):
      #OK

1

To match the beginning and end of a string, simply use the str.endswith and str.startswith. If you want to do more complicated matching, look into the re module.

file = 'myfile-something.txt'

if file.startswith('myfile-') and file.endswith('.txt'):
    print('success')
Bobby Ocean
  • 3,120
  • 1
  • 8
  • 15