Pobieranie nazw wszystkich plików z folderu z Rubim

Chcę pobrać wszystkie nazwy plików z folderu używając Ruby.

Author: Željko Filipin, 2009-11-18

14 answers

Masz również opcję skrótu

Dir["/path/to/search/*"]

I jeśli chcesz znaleźć wszystkie pliki Rubiego w dowolnym folderze lub podfolderze:

Dir["/path/to/search/**/*.rb"]
 430
Author: Ian Eccles,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-11-18 13:02:29
Dir.entries(folder)

Przykład:

Dir.entries(".")

Źródło: http://ruby-doc.org/core/classes/Dir.html#method-c-entries

 143
Author: Željko Filipin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-01 08:43:48

Poniższe urywki dokładnie pokazują nazwę plików wewnątrz katalogu, pomijając podkatalogi i ".", ".." kropkowane foldery:

Dir.entries("your/folder").select {|f| !File.directory? f}
 82
Author: Emiliano Poggi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-12 19:21:43

Aby uzyskać wszystkie pliki (tylko pliki ściśle) rekurencyjnie:

Dir.glob('path/**/*').select{ |e| File.file? e }

Lub cokolwiek, co nie jest katalogiem (File.file? odrzuciłoby pliki niestandardowe):

Dir.glob('path/**/*').reject{ |e| File.directory? e }

Alternatywne Rozwiązanie

Za pomocą Find#find metoda wyszukiwania oparta na wzorcach, taka jak Dir.glob, jest rzeczywiście lepsza. Zobacz tę odpowiedź na "Jednolinijkowy do rekurencyjnej listy katalogów w Ruby?".

 30
Author: konsolebox,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:02:56

Osobiście uważam, że jest to najbardziej przydatne do zapętlania plików w folderze, patrząc w przyszłość bezpieczeństwa:

Dir['/etc/path/*'].each do |file_name|
  next if File.directory? file_name 
end
 8
Author: mr.buttons,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-12 19:20:14

To działa dla mnie:

Jeśli nie chcesz ukrytych plików[1], Użyj Dir[]:

# With a relative path, Dir[] will return relative paths 
# as `[ './myfile', ... ]`
#
Dir[ './*' ].select{ |f| File.file? f } 

# Want just the filename?
# as: [ 'myfile', ... ]
#
Dir[ '../*' ].select{ |f| File.file? f }.map{ |f| File.basename f }

# Turn them into absolute paths?
# [ '/path/to/myfile', ... ]
#
Dir[ '../*' ].select{ |f| File.file? f }.map{ |f| File.absolute_path f }

# With an absolute path, Dir[] will return absolute paths:
# as: [ '/home/../home/test/myfile', ... ]
#
Dir[ '/home/../home/test/*' ].select{ |f| File.file? f }

# Need the paths to be canonical?
# as: [ '/home/test/myfile', ... ]
#
Dir[ '/home/../home/test/*' ].select{ |f| File.file? f }.map{ |f| File.expand_path f }

Teraz, Reż.wpisy zwrócą ukryte pliki, a ty nie potrzebujesz znacznika Asterix (możesz po prostu przekazać zmienną z nazwą katalogu), ale zwróci nazwę bazową bezpośrednio, więc plik.funkcje xxx nie działają.

# In the current working dir:
#
Dir.entries( '.' ).select{ |f| File.file? f }

# In another directory, relative or otherwise, you need to transform the path 
# so it is either absolute, or relative to the current working dir to call File.xxx functions:
#
home = "/home/test"
Dir.entries( home ).select{ |f| File.file? File.join( home, f ) }

[1] .dotfile na Unixie, Nie wiem o Windows

 8
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-04 00:33:04

Jest to rozwiązanie do znajdowania plików w katalogu:

files = Dir["/work/myfolder/**/*.txt"]

files.each do |file_name|
  if !File.directory? file_name
    puts file_name
    File.open(file_name) do |file|
      file.each_line do |line|
        if line =~ /banco1/
          puts "Found: #{line}"
        end
      end
    end
  end
end
 7
Author: gilcierweb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-20 20:44:08

Podczas pobierania wszystkich nazw plików w katalogu, ten fragment może być użyty do odrzucenia obu katalogów [., ..] oraz ukryte pliki zaczynające się od .

files = Dir.entries("your/folder").reject {|f| File.directory?(f) || f[0].include?('.')}
 3
Author: Lahiru,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-12 19:18:56

W Rubim 2.5 możesz teraz używać Dir.children. Pobiera nazwy plików jako tablicę z wyjątkiem""."i ".."

Przykład:

Dir.children("testdir")   #=> ["config.h", "main.rb"]

Http://ruby-doc.org/core-2.5.0/Dir.html#method-c-children

 3
Author: Mario Pérez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-02 11:53:24

To jest to, co działa dla mnie:

Dir.entries(dir).select { |f| File.file?(File.join(dir, f)) }

Dir.entries zwraca tablicę łańcuchów. Następnie musimy podać pełną ścieżkę pliku do File.file?, chyba że {[3] } jest równe naszemu bieżącemu katalogowi roboczemu. Dlatego to File.join().

 2
Author: yegor256,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-28 16:08:26

Jeśli chcesz uzyskać tablicę nazw plików wraz z dowiązaniami symbolicznymi , użyj

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

Lub nawet

Dir.new('/path/to/dir').reject { |f| File.directory? f }

I jeśli chcesz przejść bez dowiązań symbolicznych , użyj

Dir.new('/path/to/dir').select { |f| File.file? f }

Jak pokazano w innych odpowiedziach, użyj Dir.glob('/path/to/dir/**/*') zamiast Dir.new('/path/to/dir'), Jeśli chcesz odzyskać wszystkie pliki rekurencyjnie.

 1
Author: Mike,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-04 18:05:12
def get_path_content(dir)
  queue = Queue.new
  result = []
  queue << dir
  until queue.empty?
    current = queue.pop
    Dir.entries(current).each { |file|
      full_name = File.join(current, file)
      if not (File.directory? full_name)
        result << full_name
      elsif file != '.' and file != '..'
          queue << full_name
      end
    }
  end
  result
end

Zwraca względne ścieżki pliku z katalogu i wszystkich podkatalogów

 0
Author: punksta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-21 08:43:38
Dir.new('/home/user/foldername').each { |file| puts file }
 0
Author: Ashwin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-06 07:36:11

Możesz również użyć Rake::FileList (pod warunkiem, że posiadasz rake zależność):

FileList.new('lib/*') do |file|
  p file
end

Zgodnie z API:

Fileliści są leniwi. Gdy podano listę szablonów glob dla możliwych pliki, które mają być umieszczone na liście plików, zamiast przeszukiwać plik struktury, aby znaleźć pliki, Lista plików zawiera wzorzec dla tych ostatnich użyj.

Https://docs.ruby-lang.org/en/2.1.0/Rake/FileList.html

 0
Author: Artur Beljajev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-24 10:32:48