TransWikia.com

ResetDirectory causes a fail on stored file names

Mathematica Asked on February 26, 2021

Consider some directory dir with sub dirs and files. Our aim is to count the no of files in dir (not in sub-dirs, just the dir.)

dir="C:/folder";
SetDirectory[dir];
names = FileNames[];
Length@Select[names, FileType@# == File&]
(*2*)

There were in fact 2 files and 6 sub-dirs.

FileType /@ names // Tally
(*{{Directory, 6}, {File, 2}}*)

Now consider the following code

dir = "C:/folder";
SetDirectory[dir];
names = FileNames[];
ResetDirectory[];
Length@Select[names, FileType@# == File &]
(*0*)

Here even though we saved the file names in names, the count is 0. Why is this? Why is a directory reset affecting stored file names?

One Answer

Herein lies the issue:

In[6]:= SetDirectory[$UserDocumentsDirectory];
files = FileNames[];
SetDirectory[$UserBaseDirectory];
CountsBy[files, FileExistsQ]

Out[9]= <|False -> 54, True -> 1|>

The filenames returned by FileNames are given relative to the current path, and so when the path changes they aren't valid filenames.

To get around this limitation, use ExpandFileName to make sure you always have an absolute file path. In the above, use

files = ExpandFileName /@ FileNames[];

In the snippet above the only file that returns True from FileExistsQ is easily guessed by any OSX user:

In[11]:= Select[files, FileExistsQ]

Out[11]= {".DS_Store"}
```

Correct answer by Jason B. on February 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP