Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

At the moment I'm using >

filename = FileNameJoin[{root = "F:\\somefolderpath", file = "somefile.extention"}];
If[! DirectoryQ[root], 
  Print[Style["Directory '" <> root <> "' does not exist!", {Red, Bold, Large}]]; Quit[]];
If[! FileExistsQ[filename], 
  Print[Style["File '" <> filename <> "' does not exist!", {Red, Bold, Large}]]; Quit[]];
(*Start using 'filename'*)

edit: Ended up using

SafeFile::usage = "Use instead of Import.";
SafeFile::nodir = "Directory `1` does not exist.";
SafeFile::nofile = "File `1` does not exist.";
SafeFile[filename_,root_:NotebookDirectory[]]:=Module[{
    fullfilename=FileNameJoin[{root,filename}]
},
    If[!TrueQ@DirectoryQ@root,Message[SafeFile::nodir,root];Quit[]];
    If[!TrueQ@FileExistsQ@fullfilename,Message[SafeFile::nofile,filename];Quit[]];
    Import[fullfilename]
]

Quitting kernel was actually what I needed.

share|improve this question
    
Please paste the actual code instead of a screenshot. –  Brett Champion Apr 13 '12 at 22:01
    
The messages would usually be named SafeFile::nodir, and you don't need to define them in your function; they can go right next to the SafeFile::usage definition. –  Brett Champion Apr 13 '12 at 22:06
add comment

2 Answers 2

up vote 11 down vote accepted

You might consider using Messages instead of Print. You should also consider using TrueQ if either root or filename might not be a string.

file::nodir = "Directory `1` does not exist.";
file::nofile = "File `1` does not exist.";

If[! TrueQ @ DirectoryQ @ root, Message[file::nodir, root]; Abort[]];
If[! TrueQ @ FileExistsQ @ filename, Message[file::nofile, filename]; Abort[]];
share|improve this answer
add comment

What you are doing seems pretty minimal already; the fact that MMA notation is very verbose is something that cannot be avoided. You could separate the whole check into a separate function and put that into an invisible initialization cell so it is out of the way.

As for not killing the kernel, just use Abort[] instead of Quit[].

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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