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 re
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) }
Dir.glob('*').select { |fn| File.file?(fn) }
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.
Entries don't do rescursion i think. If you want the files in the subdirs also use
puts Dir['**/*'].select { |f| File.file?(f) }
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.
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) }