【问题标题】:Search for files in a folder搜索文件夹中的文件
【发布时间】:2013-12-27 09:16:11
【问题描述】:

我正在尝试使用 Julia 解析大量文本文件,并且我想遍历一个文件名数组,而不是键入一个函数调用来单独读取每个文件。到目前为止,我一直无法找到一种方法来在文件夹中搜索与模式匹配的文件。

是否有一个基础库 Julia 函数可以返回给定文件夹中的所有文件名,匹配给定的字符串模式?

R 中的等效函数是 list.files(),如果这有助于传达我想要的内容。

【问题讨论】:

  • MDe,您可能会考虑更新您的答案。 @Trock 的答案中的 Glob.jl 包比 oneliner hack 更直接和可读。

标签: julia


【解决方案1】:

在 Julia 中,list.files() 等价于 readdir([path])

据我所知,没有内置的目录搜索,但它是单行的:

searchdir(path,key) = filter(x->contains(x,key), readdir(path))


更新:至少从 Julia v0.7 开始,contains() 已被 occursin(substring, string) 弃用。所以上面的过滤器现在是:

searchdir(path,key) = filter(x->occursin(key,x), readdir(path))

【讨论】:

  • 作为补充:类似于contains,以下函数可能有用:isfileisdirstartswithendswith
  • 您也可以使用readdir(expanduser(path))~ 转换为主目录(Linux 下)。也可以使用正则表达式:searchdir("~/Package/MyPackage/src/",r".jl$")
【解决方案2】:

另一种解决方案是使用Glob.jl 包。例如,如果您的目录中有以下文件列表:

foo1.txt
foo2.txt
foo3.txt
bar1.txt
foo.jl

你想找到所有以“foo”开头的文本文件

using Glob
glob("foo*.txt") #if searching the working directory
#output:
#"foo1.txt"
#"foo2.txt"
#"foo3.txt"
glob("foo*.txt","path/to/dir") #for specifying a different directory
#output:
#"path/to/dir/foo1.txt"
#"path/to/dir/foo2.txt"
#"path/to/dir/foo3.txt"

【讨论】: