0

I am looking for a python script that will find the the exact filename of an existing file in the current directory that this python script will run from, that may be named incrementally.

For example the file could be: file1.dat file2.dat file3.dat ....

So we know that the file name starts with the prefix file and we know that it ends with the sufix .dat.

But we don't know whether it will be file1.dat or file1000.dat or anything inbetween.

So I need a script that will check in the range of say 1-1000 all filenames from file1.dat to file1000.dat, and if it finds the one that does exist in the directory, it returns a success message.

Gabrielf1
  • 157
  • 1
  • 2
  • 5
  • 1
    Maybe take a look to the module `glob` – PRMoureu Aug 29 '17 at 18:38
  • 1
    have a look here : https://stackoverflow.com/questions/3964681/find-all-files-in-a-directory-with-extension-txt-in-python – Dadep Aug 29 '17 at 18:38
  • Possible duplicate of [Find all files in a directory with extension .txt in Python](https://stackoverflow.com/questions/3964681/find-all-files-in-a-directory-with-extension-txt-in-python) – Dadep Aug 29 '17 at 18:39

4 Answers4

8

Try something like this:

import os

path = os.path.dirname(os.path.realpath(__file__))

for f_name in os.listdir(path):
    if f_name.startswith('file') and f_name.endswith('.dat'):
        print('found a match')
4

I would search with a regex using Python's glob module. Here's a sample expression:

glob.glob(r'^file(\d+)\.dat$')

This will match a filename starting with file, followed by any digits, and ending with .dat. For a deeper explanation on how this regex works, check it out on Regex101, where you can test it, as well.

Note: Your question did not specify, but as a bonus, glob also supports recursive searches.

Zach Gates
  • 4,045
  • 1
  • 27
  • 51
2

Try this:

for i in range(1, 1001):
    if os.path.isfile("file{0}.dat".format(i)):
        print("Success!")
        break
else:
    print("Failure!")
Karan Elangovan
  • 688
  • 1
  • 7
  • 14
0

As others have suggested in comments, glob and other options are available,however, personally i find listdir more comfortable.

import os
for file in os.listdir("/DIRECTORY"):
    if file.endswith(".dat") and prefix in file:
        print file
user5722540
  • 590
  • 8
  • 24
  • What is `prefix`? I suspect it's `"file"`, and if that is the case, you could end up matching files like `file-sample.dat`, etc. Using the `in` operator, you could even match files like `sample-file.dat` or `ignore-this-file.dat`. – Zach Gates Aug 29 '17 at 18:57