Ruby文件完整路径
问题描述:
我正在编写一个程序,在该程序中,我遍历目标文件夹的子文件夹中的所有文件,并执行其中写入的内容。所以,我的本地文件夹看起来像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
答
好了完整的代码,我可能已经找到的东西,但它看起来丑陋因此,如果任何人有通过各种手段更好的解决方案去先。
我编辑我read_folder方法来解析完整路径READ_FILE方法如下:
def read_folder(folder)
Dir.foreach(folder){ |file|
next if File.extname(file) != ".gbk"
path = File.absolute_path(folder)+'/'+File.basename(file)
temp = read_file(path)
$bacteria_specs[0] += temp[0]
$bacteria_specs[1] += temp[1]
}
return $bacteria_specs
end
而且我得到我期望的路径。 (尽管我打电话给C程序仍然失败,所以我不得不去检查其他地方:D)
可能不是你的问题的原因,但我认为你可以用一次调用替换'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