3
$\begingroup$

I have multiple pictures I would like to import all at once. The filenames range from "000001.tif" to "000200.tif." I am having a hard time importing multiple images after looking up the filenames and modifying which ranges I would like to import.

So far I've done the following:

names=FileBaseName /@ FileNames["*.tif"];
Flatten@ToExpression@StringSplit[names, ","];
Select[%, 20 <= # <= 22 &]

{"20", "21", "22"}

n = ToString /@ HoldForm /@ Unevaluated@%;
nn = StringTemplate["0000``"] /@ n

{"000020", "000021", "000022"}

From here when I try to import these files, mathematica merges them into one text.

Import[nn <> ".tif"] 

Import::nffil: File 000020000021000022.tif not found during Import.

How can I import from a string and grab multiple files? And when I try to change the string {"000020", "000021", "000022"} to a list, I always loose the 0s.

Any help is very appreciated, thanks

$\endgroup$
1
  • 1
    $\begingroup$ Import[#<>".tif"]&/@nn $\endgroup$
    – N.J.Evans
    Jul 28, 2022 at 16:17

2 Answers 2

5
$\begingroup$

From a list of substrings

Import[
    StringTemplate["``.TIF"]@StringPadLeft[#,6,"0"]
    ,"TIF"
]& /@ {"20","21","22"}

Search for files with a pattern name

Here I save not only the data (image), but also some meta-data.

ClearAll[alldata];
alldata = Table[
    With[
        {
            filename=StringTemplate["``.TIF"]@ToString@NumberForm[k,{6,0},NumberPadding->"0"]
        },
        If[
            FileExistsQ[filename],
            <|
                "name"->filename, 
                "data"->Import[filename, "TIF"]
            |>,
            Nothing
        ]
    ]
    ,{k,100}
]

or

From a list of files that exist

Even more metadata

ClearAll[fn,alldata];
alldata=Table[
    <|
        "name"-> fn,
        "size"-> FileSize[fn],
        "data"->Import[fn,"TIF"]
    |>
    ,{fn,FileNames["*.TIF"]}
]
$\endgroup$
1
$\begingroup$

Assuming you want to import all the files in some given directory. Here is a simple example with just 2 files:

dir = "d:/tmp/t2";
names = FileNames[All, dir];
Import[#] & /@ names
$\endgroup$

Your Answer

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

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