从使用Ruby的文件夹中获取所有文件的名称

时间:2023-01-14 11:22:09

I want to get all file names from a folder using Ruby.

我想使用Ruby从一个文件夹中获取所有文件名。

14 个解决方案

#1


413  

You also have the shortcut option of

你也可以选择快捷方式。

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

and if you want to find all Ruby files in any folder or sub-folder:

如果你想在任何文件夹或子文件夹中找到所有的Ruby文件:

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

#2


135  

Dir.entries(folder)

example:

例子:

Dir.entries(".")

Source: http://ruby-doc.org/core/classes/Dir.html#method-c-entries

来源:http://ruby-doc.org/core/classes/Dir.html method-c-entries

#3


77  

The following snippets exactly shows the name of the files inside a directory, skipping subdirectories and ".", ".." dotted folders:

下面的代码片段显示了目录中文件的名称,跳过了子目录和“”。,“. .”虚线文件夹:

Dir.entries("your/folder").select {|f| !File.directory? f}

#4


28  

To get all files (strictly files only) recursively:

递归地获取所有文件(仅限文件):

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

Or anything that's not a directory (File.file? would reject non-regular files):

或者不是目录的文件?会拒绝非正式文件):

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

Alternative Solution

Using Find#find over a pattern-based lookup method like Dir.glob is actually better. See this answer to "One-liner to Recursively List Directories in Ruby?".

使用基于模式的查找方法,如Dir。水珠是更好的。请参见“在Ruby中递归地列出目录的一行程序?”

#5


8  

Personally, I found this the most useful for looping over files in a folder, forward looking safety:

就我个人而言,我发现这对于在文件夹中循环文件、前瞻性安全是最有用的:

Dir['/etc/path/*'].each do |file_name|
  next if File.directory? file_name 
end

#6


7  

This works for me:

这工作对我来说:

If you don't want hidden files[1], use Dir[]:

如果您不想要隐藏文件[1],请使用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 }

Now, Dir.entries will return hidden files, and you don't need the wildcard asterix (you can just pass the variable with the directory name), but it will return the basename directly, so the File.xxx functions won't work.

现在,Dir。条目将返回隐藏的文件,并且您不需要通配符asterix(您可以只使用目录名传递变量),但是它将直接返回basename,因此文件。xxx功能不能工作。

# 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 on unix, I don't know about Windows

unix上的[1].dotfile,我不知道Windows

#7


6  

This is a solution to find files in a directory:

这是一个在目录中查找文件的解决方案:

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

#8


3  

While getting all the file names in a directory, this snippet can be used to reject both directories [., ..] and hidden files which start with a .

在获取目录中的所有文件名时,可以使用此代码段来拒绝两个目录[。,. .和以a开头的隐藏文件。

files = Dir.entries("your/folder").reject {|f| File.directory?(f) || f[0].include?('.')}

#9


1  

If you want get an array of filenames including symlinks, use

如果您想获得包含符号链接的文件名数组,请使用

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

or even

甚至

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

and if you want to go without symlinks, use

如果你想不使用符号链接,请使用

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

As shown in other answers, use Dir.glob('/path/to/dir/**/*') instead of Dir.new('/path/to/dir') if you want to get all the files recursively.

如其他答案所示,如果希望递归地获取所有文件,请使用Dir.glob('/path/to/dir/**/*')而不是Dir.new('/path/to/dir')。

#10


1  

This is what works for me:

这对我很有效:

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

Dir.entries returns an array of strings. Then, we have to provide a full path of the file to File.file?, unless dir is equal to our current working directory. That's why this File.join().

Dir。条目返回一个字符串数组。然后,我们必须提供文件到文件的完整路径。,除非dir等于当前工作目录。这就是为什么这个File.join()。

#11


1  

In Ruby 2.5 you can now use Dir.children. It gets filenames as an array except for "." and ".."

在Ruby 2.5中,您现在可以使用Dir.children。它获取文件名作为数组,除了“.”和“.. .”

Example:

例子:

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

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

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

#12


0  

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

returns file's relative paths from directory and all subdirectories

从目录和所有子目录返回文件的相对路径

#13


0  

Dir.new('/home/user/foldername').each { |file| puts file }

#14


0  

You may also want to use Rake::FileList (provided you have rake dependency):

您也可以使用Rake::FileList(如果您有Rake依赖项):

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

According to the API:

根据API:

FileLists are lazy. When given a list of glob patterns for possible files to be included in the file list, instead of searching the file structures to find the files, a FileList holds the pattern for latter use.

文件列表是懒惰。当给出文件列表中可能包含的文件的glob模式列表时,文件列表将保存用于后一种使用的模式,而不是搜索文件结构来查找文件。

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

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

#1


413  

You also have the shortcut option of

你也可以选择快捷方式。

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

and if you want to find all Ruby files in any folder or sub-folder:

如果你想在任何文件夹或子文件夹中找到所有的Ruby文件:

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

#2


135  

Dir.entries(folder)

example:

例子:

Dir.entries(".")

Source: http://ruby-doc.org/core/classes/Dir.html#method-c-entries

来源:http://ruby-doc.org/core/classes/Dir.html method-c-entries

#3


77  

The following snippets exactly shows the name of the files inside a directory, skipping subdirectories and ".", ".." dotted folders:

下面的代码片段显示了目录中文件的名称,跳过了子目录和“”。,“. .”虚线文件夹:

Dir.entries("your/folder").select {|f| !File.directory? f}

#4


28  

To get all files (strictly files only) recursively:

递归地获取所有文件(仅限文件):

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

Or anything that's not a directory (File.file? would reject non-regular files):

或者不是目录的文件?会拒绝非正式文件):

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

Alternative Solution

Using Find#find over a pattern-based lookup method like Dir.glob is actually better. See this answer to "One-liner to Recursively List Directories in Ruby?".

使用基于模式的查找方法,如Dir。水珠是更好的。请参见“在Ruby中递归地列出目录的一行程序?”

#5


8  

Personally, I found this the most useful for looping over files in a folder, forward looking safety:

就我个人而言,我发现这对于在文件夹中循环文件、前瞻性安全是最有用的:

Dir['/etc/path/*'].each do |file_name|
  next if File.directory? file_name 
end

#6


7  

This works for me:

这工作对我来说:

If you don't want hidden files[1], use Dir[]:

如果您不想要隐藏文件[1],请使用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 }

Now, Dir.entries will return hidden files, and you don't need the wildcard asterix (you can just pass the variable with the directory name), but it will return the basename directly, so the File.xxx functions won't work.

现在,Dir。条目将返回隐藏的文件,并且您不需要通配符asterix(您可以只使用目录名传递变量),但是它将直接返回basename,因此文件。xxx功能不能工作。

# 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 on unix, I don't know about Windows

unix上的[1].dotfile,我不知道Windows

#7


6  

This is a solution to find files in a directory:

这是一个在目录中查找文件的解决方案:

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

#8


3  

While getting all the file names in a directory, this snippet can be used to reject both directories [., ..] and hidden files which start with a .

在获取目录中的所有文件名时,可以使用此代码段来拒绝两个目录[。,. .和以a开头的隐藏文件。

files = Dir.entries("your/folder").reject {|f| File.directory?(f) || f[0].include?('.')}

#9


1  

If you want get an array of filenames including symlinks, use

如果您想获得包含符号链接的文件名数组,请使用

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

or even

甚至

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

and if you want to go without symlinks, use

如果你想不使用符号链接,请使用

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

As shown in other answers, use Dir.glob('/path/to/dir/**/*') instead of Dir.new('/path/to/dir') if you want to get all the files recursively.

如其他答案所示,如果希望递归地获取所有文件,请使用Dir.glob('/path/to/dir/**/*')而不是Dir.new('/path/to/dir')。

#10


1  

This is what works for me:

这对我很有效:

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

Dir.entries returns an array of strings. Then, we have to provide a full path of the file to File.file?, unless dir is equal to our current working directory. That's why this File.join().

Dir。条目返回一个字符串数组。然后,我们必须提供文件到文件的完整路径。,除非dir等于当前工作目录。这就是为什么这个File.join()。

#11


1  

In Ruby 2.5 you can now use Dir.children. It gets filenames as an array except for "." and ".."

在Ruby 2.5中,您现在可以使用Dir.children。它获取文件名作为数组,除了“.”和“.. .”

Example:

例子:

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

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

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

#12


0  

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

returns file's relative paths from directory and all subdirectories

从目录和所有子目录返回文件的相对路径

#13


0  

Dir.new('/home/user/foldername').each { |file| puts file }

#14


0  

You may also want to use Rake::FileList (provided you have rake dependency):

您也可以使用Rake::FileList(如果您有Rake依赖项):

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

According to the API:

根据API:

FileLists are lazy. When given a list of glob patterns for possible files to be included in the file list, instead of searching the file structures to find the files, a FileList holds the pattern for latter use.

文件列表是懒惰。当给出文件列表中可能包含的文件的glob模式列表时,文件列表将保存用于后一种使用的模式,而不是搜索文件结构来查找文件。

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

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