MathGroup Archive 2007

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: checking, if a file exists

  • To: mathgroup at
  • Subject: [mg84398] Re: checking, if a file exists
  • From: Bill Rowe <readnewsciv at>
  • Date: Fri, 21 Dec 2007 03:22:56 -0500 (EST)

On 12/20/07 at 4:50 PM, vejrazka at wrote:

>I am new to Mathematica & I have the following problem: I need to 1.
>check, if a file ("data.dat") with some computationally intensive
>results exists 2. if yes, read the file 3. if no, do the calculation

>I have written (in Mathematica 6) the following:

>fileName = "...some path ... \\data.dat"; data =
>If[FileType[fileName] == File, Import[fileName],

>It reads correctly the data if the file exists. But if the file does
>not exists, it returns

>If[None == File, Import[fileName], calculate[0]]

>Evidently, the problem is, that

>FileType[fileName] == File

>returns correctly True if the file exists, but it does not return
>False when the file is missing -- it returns only None == File.

>How to do that?

The problem here is FileType returns a symbol rather than a
string or a specific value. Equality is undetermined when the
arguments are two symbols that have no assigned values.
Consequently, Mathematica cannot perform the desired evaluation.

There are several solutions.

Instead of using Equal use SameQ. This will yield False for
symbols with no assigned values if the symbols are not
identical. That is

If[None === File, Import[fileName], calculate[0]]

will do what you want.

Another approach would be to use MemberQ[FileNames[],filename]
as the test. This will return True if filename is one of the
files in the current working directory and False otherwise. It
seems to me this is the better test since it directly tests for
what you are interested in and can only return True or False.
To reply via email subtract one hundred and four

  • Prev by Date: Re: ClearAll[f]; f[x_] := x^2; f[y_] :=y^4; (*What is:*) f[2]
  • Next by Date: Re: ClearAll[f]; f[x_] := x^2; f[y_] :=y^4; (*What is:*) f[2]
  • Previous by thread: Re: checking, if a file exists
  • Next by thread: using Dsolve for equation: y'' + |y|^2y=ay