Ruby - 读取计算文件

时间:2017-04-21 11:02:15

标签: ruby file

想象一下,我有一堆文件

a_1, a_2, ..., a_n
b_1, b_2, ..., b_n

我的脚本需要按以下顺序读取文件:

a_1, b_1, a_2, b_2, ..., a_n, b_n

我知道在指定名称时如何读取文件。即File.open("a_1.txt", "r"),但我可以指定名称,以便我有一个类似

的循环
while i < n
   File.open("a_i.txt", "r")
   do sth
end

6 个答案:

答案 0 :(得分:3)

您可以获取文件的基本名称,分为_并按[number, letter]排序:

# filenames = Dir.glob('input/*')
filenames = ["input/a_6", "input/b_8", "input/b_7", "input/a_3", "input/a_4", "input/b_4", "input/b_9", "input/b_1", "input/b_11", "input/a_11", "input/b_3", "input/b_2", "input/a_1", "input/b_6", "input/b_12", "input/a_8", "input/a_2", "input/a_9", "input/a_5", "input/b_10", "input/a_7", "input/b_5", "input/a_10", "input/a_12"]

filenames.sort_by! do |filename|
  letter, number = File.basename(filename).split('_')
  [number.to_i, letter]
end

p filenames
# ["input/a_1", "input/b_1", "input/a_2", "input/b_2", "input/a_3", "input/b_3", "input/a_4", "input/b_4", "input/a_5", "input/b_5", "input/a_6", "input/b_6", "input/a_7", "input/b_7", "input/a_8", "input/b_8", "input/a_9", "input/b_9", "input/a_10", "input/b_10", "input/a_11", "input/b_11", "input/a_12", "input/b_12"]

我通常喜欢将输入文件和脚本放在不同的文件夹中。

最后,由于"3".to_i"3.txt".to_i都返回3,因此此代码适用于任何扩展程序(包括无扩展程序)。

答案 1 :(得分:1)

我会做这样的事情:

file_names = (1..5).to_a.product(%w[a b]).map { |(a, b)| "#{b}_#{a}.txt" }

file_names.each do |file_name|
  # File.open(file_name, 'r')
end

必须使用5替换n

或者您可能想要使用嵌套循环:

(1..5).each do |n|
  %w[a b].each do |c|
    # File.open("#{c}_#{n}.txt", 'r')
  end
end

答案 2 :(得分:1)

如果您事先并不确切知道将要存在哪些文件,您可能需要对目录列表进行排序。

files = Dir["/path/to/files/*.txt"].sort_by{|f| [f[\d+].to_i, f]}
#=> ["a_1.txt", "b_1.txt", "a_2.txt", "b_2.txt", ...]

按文件名中的数字排序,然后按名称本身排序。然后你只需按数组顺序打开它们。

答案 3 :(得分:0)

 > files = Dir["/path/to/files/*.txt"]
 #=> ["a_5", "b_2", "b_9", "b_1", "b_10", "b_3", "b_5", "b_8", "a_1", "a_3", "a_8", "a_6", "a_2", "a_7", "b_6", "b_7", "b_4", "a_10", "a_4", "a_9"] 
 > files_in_order = files.group_by{|e| e.split("_").last.to_i}.sort.map{|v| v[1].sort}.flatten
 #=> ["a_1", "b_1", "a_2", "b_2", "a_3", "b_3", "a_4", "b_4", "a_5", "b_5", "a_6", "b_6", "a_7", "b_7", "a_8", "b_8", "a_9", "b_9", "a_10", "b_10"]

答案 4 :(得分:0)

出于好奇,没有明确排序:

Dir["/path/to/files/*.txt"].chunk { |e| e.split("_").first }
                           .map(&:last)
                           .reduce(&:zip)
                           .flatten

答案 5 :(得分:-1)

您需要的代码是:

while i < n
   File.open("a_#{i}.txt", "r") { |file|
      do sth
   }
end

在字符串中,当您在其中放入“#{expr}”时,将评估expr的值并在运行时填充。 例如:

>irb
irb(main):001:0> i = 5
=> 5
irb(main):002:0> "a_#{i}"
=> "a_5"