1
$\begingroup$

I thought I write a super-simple program to import all (Excel)files from a directory a user can choose>

Manipulate[
 dirName = SetDirectory[DirectoryName[importOneFileName]];
 dataFiles = FileNames["*.xls*", dirName]

 , {{importOneFileName, "", "Load Files"}, FileNameSetter[#] &}
 ]

This is actually working. However, I always get an error messages regarding the SetDirectory[]. I can, of course, write

Quiet@SetDirectory[DirectoryName[importOneFileName]]

which works. But having an error message always seems odd. I found that others have similar problems with FileNameSetter[]. Maybe Quiet is the best that can be done here.

$\endgroup$
7
  • $\begingroup$ Why not just do this? Doesn't it accomplish the same thing, in much less code? DynamicModule[{selectedDir}, Column[{FileNameSetter[Dynamic[selectedDir], "Directory"], Dynamic[FileNames["*.xlsx", selectedDir]]}]] $\endgroup$
    – ktm
    Commented Sep 11, 2018 at 13:02
  • $\begingroup$ Most likely ... I know how to use Manipulate, but haven't had time to properly dive into Dynamics, although it seems much more flexible. But thanks so far! $\endgroup$ Commented Sep 11, 2018 at 13:07
  • $\begingroup$ I believe it is a more straightforward way to achieve what you're after. $\endgroup$
    – ktm
    Commented Sep 11, 2018 at 13:08
  • $\begingroup$ just change FileNameSetter[#] & to FileNameSetter[#, "Directory"] &? $\endgroup$
    – kglr
    Commented Sep 11, 2018 at 13:12
  • $\begingroup$ @kglr Simplifies the code, which is nice, but the error message is still there. $\endgroup$ Commented Sep 11, 2018 at 13:31

2 Answers 2

1
$\begingroup$

Just don't run the code if the file name is not set:

Manipulate[
  If[
    FileExistsQ @ importOneFileName,

    dirName = SetDirectory[DirectoryName[importOneFileName]];
    dataFiles = FileNames["*.xls*", dirName],

    ""
  ], 
  {{importOneFileName, " ", "Load Files"}, FileNameSetter[#] &  }
]
$\endgroup$
1
$\begingroup$

You may use SystemDialogInput with the "Directory" input type to have the user select a directory directly. Check a directory has been chosen by comparing the result to $Canceled.

dir = SystemDialogInput["Directory"];
If[dir =!= $Canceled,
 "Process directory",
 "No directory to process"
 ]

Hope this helps.

$\endgroup$

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.