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

前端 未结 8 543
走了就别回头了
走了就别回头了 2021-01-03 21:10

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

相关标签:
8条回答
  • 2021-01-03 21:13

    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) }
    
    0 讨论(0)
  • 2021-01-03 21:21

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

    0 讨论(0)
  • 2021-01-03 21:25

    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.

    0 讨论(0)
  • 2021-01-03 21:25

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

    puts Dir['**/*'].select { |f| File.file?(f) }
    
    0 讨论(0)
  • 2021-01-03 21:28

    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 讨论(0)
  • 2021-01-03 21:29

    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) }
    
    0 讨论(0)
提交回复
热议问题