开发者

How do I get a listing of only files using Dir.glob?

开发者 https://www.devze.com 2023-04-11 11:30 出处:网络
How can I return a list of only the files, not directories, in a specified directory? I have my_list = Dir.glob(script_path.join(\"*\"))

How can I return a list of only the files, not directories, in a specified directory?

I have my_list = Dir.glob(script_path.join("*"))

This returns everything in the directory,including s开发者_JAVA技巧ubdirectories. I searched but haven't been able to find the answer.


In addition to Mark's answer, Dir.entries will give back directories. If you just want the files, you can test each entry to see if it's a file or a directory, by using file?.

Dir.entries('/home/theiv').select { |f| File.file?(f) }

Replace /home/theiv with whatever directory you want to look for files in.

Also, have a look at File. It provides a bunch of tests and properties you can retrieve about files.


Dir.glob('*').select { |fn| File.file?(fn) }


Entries don't do rescursion i think. If you want the files in the subdirs also use

puts Dir['**/*'].select { |f| File.file?(f) }


If you want to do it in one go instead of first creating an array and then iterating over it with select, you can do something like:

my_list = []
Dir.foreach(dir) { |f| my_list << f if File.file?(f) }


Following @karl-li 's suggestion in @theIV solution, I found this to work well:

Dir.entries('path/to/files/folder').reject { |f| File.directory?(f) }


You can use Dir[]/Dir.glob or Dir.entries to get file listing. The difference between them is the former returns complete path, and the latter returns only filename.

So be careful about the following mapping segment .select {|f| File.file?(f)}: with complete path it works well, while with only filename, it sometimes works wired.

FYR:

Dir[], Dir.glob, Dir.entries


you can basically just get filenames with File.basename(file)

Dir.glob(script_path.join("*")).map{ |s| File.basename(s) }


It sounds like you're looking for Dir.entries:

Returns an array containing all of the filenames in the given directory. Will raise a SystemCallError if the named directory doesn’t exist.

If searching Google for how to solve this problem isn't turning up any results, you can look through the Ruby documentation.

0

精彩评论

暂无评论...
验证码 换一张
取 消