我正在編寫一個程序,在該程序中,我遍歷目標文件夾的子文件夾中的所有文件,並執行其中寫入的內容。所以,我的本地文件夾看起來像Ruby文件完整路徑
Folder
--Subfolder
---File
---File
---File
--Subfolder
---File
.
.
.
所以我有一個Each循環遍歷所有子文件夾和每個子文件夾我打電話,基本上做同樣的事情的方法,但在子文件夾,並呼籲每個文件的另一個方法(解析它是我通過Dir.foreach(folder){ |file| method(file)}
命令獲得的文件參數)。
所以它看起來像這樣:
Dir.foreach(Dir.pwd){ |folder| call_method(folder) }
def call_method(folder) Dir.foreach(folder){|file| reading_method(file) } end
這最後調用的方法(reading_method)應該打開稱作C方法和分析作爲參數文件的完整路徑(從而使C程序可以打開它),所以我在reading_method中使用File.absolute_path(file)
,但不是按照我的意願返回C:/folder/subfolder/file
,而是跳過C:/folder/file
跳過子文件夾(因此C程序無法執行)。
有沒有辦法獲得該文件的完整路徑?
感謝您的幫助
編輯:這裏是問
## Module
module GBK_Reader
PATH = "Z:/Folder/"
SAFETY = true
SAFETY_COUNT = 10
end
## Methods definitions
def read_file(file)
path = File.absolute_path(file)
c_string = `C:/Code/GBK_Reader/bin/Debug/GBK_Reader.exe #{path}`
return c_string.split(/ /).collect!{|spec| spec.to_i}
end
def read_folder(folder)
Dir.foreach(folder){ |file|
next if File.extname(file) != ".gbk"
temp = read_file(file)
#$bacteria_specs[0] += temp[0]
#$bacteria_specs[1] += temp[1]
}
return $bacteria_specs
end
## Main
# Look for folder
Dir.chdir(GBK_Reader::PATH)
puts "Directory found"
# Cycle through all sub-folders
$high_gc = {} #Hash to store high GC content bacterias
$count = 0
puts "Array variable set"
Dir.foreach(Dir.pwd){ |file|
next if file == "." || file == ".."
break if $count >= GBK_Reader::SAFETY_COUNT
$count += 1 if GBK_Reader::SAFETY
$bacteria_specs = [0.00, 0.00, 0.00]
$path = File.expand_path(file)
if File.directory?(file)
# Cycle through all .gbk files in sub-folder and call C program
read_folder(file)
else
# Call C program to directly evaluate GC content
c_string = read_file(file) if File.extname(file) == ".gbk"
$bacteria_specs[0] = c_string[0].to_i
$bacteria_specs[1] = c_string[1].to_i
end
# Evaluate GC content and store suitable entries
$bacteria_specs[2] = ($bacteria_specs[0]/$bacteria_specs[1])*100.00
$high_gc[file] = $bacteria_specs if $bacteria_specs[2] > 60
}
# Display suitable entries
puts "\n\n\n"
puts $high_gc
gets.chomp
可能不是你的問題的原因,但我認爲你可以用一次調用替換'Dir.foreach'調用'Dir.glob('*/*')' – Stefan 2014-10-08 15:08:35
你能顯示完整的代碼嗎?您的示例代碼在我的機器上正常工作。 – rohit89 2014-10-08 18:24:41
感謝您的回答。我不想使用Dir.glob,因爲我需要按文件夾讀取我的文件文件夾(並根據文件的「總體結果」在一個文件夾中執行操作,並且Dir.glob似乎返回所有匹配的文件的列表該模式。\ n我編輯了我的開場白以顯示完整的代碼。 – 2014-10-10 12:40:37