1
$\begingroup$

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.

Question:

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

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

1 Answer 1

4
$\begingroup$

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] 
$\endgroup$
1
  • 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$ Commented Feb 4, 2021 at 10:25

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.