mmv
June 20, 2021, 9:47pm
1
Hi! I m trying to list the regular files in the current or parent directory, to the exclusion of directories and subdirectories, using the relative paths “.” and “…”, with mixed results:
julia> pwd()
"/Users/michel/Codes/Julia/parent/child"
shell> ls
c_file1 c_file2
shell> ls ..
child p_file
julia> filter(x -> isfile(x), readdir("."))
2-element Vector{String}:
"c_file1"
"c_file2"
julia> filter(x -> isfile(x), readdir(".."))
String[]
Why is this command working as expected with “.” but not returning the name of the file (p_file) in the parent directory “…”? Thanks for any clarification.
Because isfile
is provided the filename of a file which is not in the current directory.
When you use readdir("..",join=true)
it should work as the full path is passed to isfile
.
mmv
June 21, 2021, 9:25am
3
@feanor12 : Thanks for answering. Indeed:
julia> filter(x -> isfile(x), readdir(".."))
String[]
julia> filter(x -> isfile(x), readdir("..", join = true))
1-element Vector{String}:
"../p_file"
and also
julia> filter(x -> isfile("../" * x), readdir(".."))
1-element Vector{String}:
"p_file"
Or put another way,
filter(x -> isfile(x), readdir(d))
will only do what you expect if d
is effectively the same as your current directory, e.g. "."
or the absolute path to your current directory.
What you should do instead is either
filter(x -> isfile(joinpath(d, x)), readdir(d))
or
filter(x -> isfile(x), readdir(d, join = true))
depending on whether you want full paths in the result for further processing.
mmv
June 21, 2021, 9:30am
5
@GunnarFarneback : Great! Even better. Thanks a lot.
sijo
June 21, 2021, 11:29am
6
Note that
filter(x -> isfile(x), readdir(d, join = true))
can be simplified to
filter(isfile, readdir(d, join = true))
mmv
June 21, 2021, 3:06pm
7
@sijo : Very interesting. I did not know this was even allowed… This being said, I’m also working on a Mac, which creates “hidden files” that I want to filter out too, like this:
filter(x -> isfile(joinpath(fpath, x)) && x != ".DS_Store", readdir(fpath, join = false)))
so I guess in need to keep the x
notation in order to use it in the subsequent test… unless there is another trick to be learned!
Thanks for your input.