Tuesday, June 9, 2015

File Operations: Find and Print Files in Mathematica

It's easy to find files in Mathematica with FindFiles and wildcards. The only thing you have to remember is that the 2nd argument, which specifies the directories to search must be a List even if you only specify one directory.

What did I put in my init.m files to automatically load Packages? Let's find and print init.m. A directory intended for a user's init.m file $UserBaseDirectory<>Kernel.


The wildcard will retrieve all files in the directory.


We use FilePrint to print it. Use First@ or Sequence@@ to remove the unnecessary List brackets around the filepath.

(** User Mathematica initialization file **)

Print@"Hello World from your kernel init.m file! I'm located in:\n

Print@"Loading C:\\Users\\kwcarlso\\AppData\\Roaming\\Mathematica\\Scribble.m\n"

Print@"Loading C:\\Users\\kwcarlso\\Dropbox\\Mathematica\\Initialization\\Pre-Load Functions.txt.\n"
<<"C:\\Users\\kwcarlso\\Dropbox\\Mathematica\\Initialization\\Pre-Load Functions.txt"

(* put this in Pre-Load Functions at some point? 
On[General::newsym] *)

Print@"Loading C:\\Program Files\\Wolfram Research\\Mathematica\\9.0\\AddOns\\ExtraPackages\\Utilities\\cleanSlate.m\n"
<<"C:\\Program Files\\Wolfram Research\\Mathematica\\9.0\\AddOns\\ExtraPackages\\Utilities\\cleanSlate.m"

Suppose we wanted to search for all files of a given type in Mathematica's default List of filepaths, $Path, like "init.m". Important! Note that $Path includes the root directory "." and my user root directory "C:\Users\kwcarlso." We don't want to search those so we find their Positions in $Path (need to add a backslash to the path separators since a single backslash tells Mathematica to treat the following character specially and a double backslash is treated as a single backslash).


Using Drop to lose the directories at the two Positions we found, we search the remaining ones but still get far too many files. You can evaluate this command in your Notebook if you wish.


So let's just specify the directories that we want with the inner List in Part.



To search all subdirectories in the directories, add a third argument, "Infinity", or an integer to limit the depth searched.


No comments:

Post a Comment