Import a file that could be in one of three directories

I want to import a file called image.png. I know it is either in dir1, dir2 or dir3

enter image description here

On unix I can easily open it using a Kleene star.

xdg-open ~/dirA/*/image.png

On mathematica I tried to add a Kleene star to the Import argument string.

 Import[$HomeDirectory <> "/dirA/*/image.png"]

But this does not work.


How to import a file that is in $1$ of $n$ directories?

  • $\begingroup$ comment to my future self: FileNames["image.png", {$HomeDirectory}, Infinity] $\endgroup$
    – conor
    Feb 10, 2021 at 22:32

1 Answer 1


Assuming dir1, dir2, etc are strings representing the directories, use

file = First[FileNames["image.png", {dir1, dir2, dir3}], $Failed]

The 2- and 3-argument forms of FileNames are pretty useful. If the $dir_i$ all live in the same parent directory, then you could use

file = First[FileNames["image.png", {parentDir}, 2], $Failed]
  • 1
    $\begingroup$ Interestingly FileNames will accept the Kleene star because it looks for files matching a string pattern. so FileNames[$HomeDirectory <> "/dirA/*/image.png"] works too! $\endgroup$
    – conor
    Feb 4, 2021 at 10:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.