[英]how to get files count in a directory using ruby
使用 ruby 如何獲取給定目錄中的文件數,文件計數應包括遞歸目錄的計數。
例如:folder1(2 個文件)-----> folder2(4 個文件)並且 folder2 在 folder1 中。 上述案例的總數應該是 6 個文件。
ruby 中是否有任何 function 可以幫我獲取這個計數。
最快的方法應該是(不包括計數目錄):
Dir.glob(File.join(your_directory_as_variable_or_string, '**', '*')).select { |file| File.file?(file) }.count
更短:
dir = '~/Documents'
Dir[File.join(dir, '**', '*')].count { |file| File.file?(file) }
您所需要的就是這個,在當前目錄中運行。
Dir["**/*"].length
它將目錄視為文件。
稍作修改和評論
Dir['**/*'].count { |file| File.file?(file) }
在 Ruby 1.9.3 中為我工作,並且更短。
至少在我的 Windows 7 盒子上,一個警告是Dir['somedir/**/*']
不起作用。 我必須使用
cd(somedir) { Dir['**/*'] }
您還可以 go 超級裸機並執行系統命令:
count = `ls -1 #{dir} | wc -l`.to_i
以下情況如何:
find. -typef|wc -l
另外,使用這個 over Dir.count 方法有什么缺點?
當前最佳答案不計算以“.”開頭的子目錄中的文件。 當我們想要計算子目錄中的文件,如'.git'或'.vs'時,我們需要使用 File::FNM_DOTMATCH 參數,但我只是初學者,沒有 50 分,所以我可以評論最佳答案。
def folder_count(folder_path)
Dir.glob("#{folder_path}/**/*", File::FNM_DOTMATCH).count { |file| File.file?(file) }
end
https://ruby-doc.org/core-2.5.0/Dir.html#method-c-5B-5D
“請注意,這不會匹配類 Unix 的隱藏文件(點文件)。為了將它們包含在匹配結果中,您必須使用 File::FNM_DOTMATCH 標志或類似“{ ,. }“。”
剛才必須找到一種方法來從網絡共享中獲取文件列表,而 Dir.glob 需要很長時間,rake gem 中的 Filelist 似乎是解決方案,基准如下。 共享在 windows 服務器上,在 Windows 10 桌面上運行腳本,Ruby 2.3.0 X64。 Netork 共享有 754 個文件,我正在尋找 320 個 CSV 文件。 一些文件位於子文件夾中。
require 'rake'
require 'benchmark'
source_path = '//server/share/**/*.csv'
puts FileList.new(source_path).size #320
puts Dir.glob(source_path).length #320
puts Dir[source_path].length #320
Benchmark.bm do |x|
x.report("FileList ") { 1.times { FileList.new(source_path) } }
x.report("Dir.glob ") { 1.times { Dir.glob(source_path) } }
x.report("Dir[] ") { 1.times { Dir[source_path] } }
end
給
user system total real
FileList 0.000000 0.000000 0.000000 ( 0.000073)
Dir.glob 0.031000 0.406000 0.437000 ( 11.324227)
Dir[] 0.047000 0.563000 0.610000 ( 11.887771)
老答案:
對於非常大的文件夾,windows 中最快的方法是使用命令行版本的搜索所有內容,不知道 Linux 是否有類似搜索所有內容。如果有,請告訴我們。
ES = 'C:\Users\...\everything\es\es.exe'
def filelist path
command = %Q{"#{ES}" "#{path}\\*"}
list = []
IO.popen(command+" 2>&1") do |pipe|
while lijn = pipe.gets
list << lijn
end
end
list
end
filelist(path).count
在此處查看相對較小文件夾(+800 個文件)的結果
Benchmark.bmbm do |x|
x.report("glob ") { filelist(path).count }
x.report("everything") { Dir.glob("#{folder}/**/*").count }
end
Rehearsal ----------------------------------------------
glob 0.000000 0.032000 0.032000 ( 0.106887)
everything 0.000000 0.000000 0.000000 ( 0.001979)
------------------------------------- total: 0.032000sec
user system total real
glob 0.016000 0.015000 0.031000 ( 0.110030)
everything 0.000000 0.016000 0.016000 ( 0.001881)
以~/Documents
為例。
一行代碼:
Dir['~/Documents'].length
對於更長的路徑,一行的可讀性可能會降低,因此:
path = '~/Documents/foo/bar'
Dir[path].length
請試試:
//we suppose that the variable folder1 is an absolute path here
pattern = File.join(folder1, "**", "*")
count = Dir.glob(pattern).count
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.