Reputation: 251
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 subdirectories. I searched but haven't been able to find the answer.
Upvotes: 24
Views: 21940
Reputation: 42192
Entries don't do rescursion i think. If you want the files in the subdirs also use
puts Dir['**/*'].select { |f| File.file?(f) }
Upvotes: 8
Reputation: 131
you can basically just get filenames with File.basename(file)
Dir.glob(script_path.join("*")).map{ |s| File.basename(s) }
Upvotes: 0
Reputation: 8212
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) }
Upvotes: 3
Reputation: 1486
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:
Upvotes: 1
Reputation: 66837
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) }
Upvotes: 4
Reputation: 25774
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.
Upvotes: 32
Reputation: 258188
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.
Upvotes: -4