【问题标题】:Iterate and print the content of all files in ruby迭代并打印 ruby​​ 中所有文件的内容
【发布时间】:2017-02-16 08:22:17
【问题描述】:

我对 Ruby 世界很陌生,所以如果它是一个简单的查询,请多多包涵。

对于我的一项任务,我希望读取文件夹中所有文本文件的内容(仅顶级),并以附加或合并的方式将文件内容重定向到单个输出文件。

我期待如下格式:

输出文件

File Name: 1st file name

all its contents
====================================
File Name: 2nd file name

all its contents
====================================
File Name: 3rd file name

all its contents
====================================
   ....
   ....


====================================

我设法编写了以下脚本,但输出文件为空。请有任何建议。

File.open('C:\Users\darkop\Desktop\final_output.txt','a') do |final|
  @files = Dir.glob("D:\text\*.txt")
  for file in @files
    text = File.open(file, 'r').read.sub(/#$/?\z/, $/)
    text.each_line do |line|
      puts "File Name:"#{file}
      puts
      final << line
      puts "=" * 20 
      end
  end
end

另外,是否可以将上述格式的输出重定向到word文档而不是文本文件?

非常感谢。

【问题讨论】:

  • 您在问题中包含了“尝试”和“预期输出”。你还应该添加你得到的“你的输出”或“错误”。
  • @JagdeepSingh:我得到空/空白输出文件。谢谢。

标签: ruby


【解决方案1】:

这应该可行。

文件名是空的,因为你有puts "File Name:"#{file}。这样#{file} 就不会被插值,因为它不在双引号内。

另外,您没有获得文件的内容,因为您只是使用了puts,而不是您想要的puts line

File.open('C:\Users\darkop\Desktop\final_output.txt','a') do |final|
  @files = Dir.glob("D:\text\*.txt")
  for file in @files
    text = File.open(file, 'r').read.sub(/#$/?\z/, $/)
    text.each_line do |line|
      puts "File Name: #{file}"
      puts
      puts line
      final << line
      puts "=" * 20 
    end
  end
end

-编辑-

由于您是 Ruby 新手,因此最好使用 each 循环,而不是 for .. in 循环。此外,只需为 Word 文档指定带有 .doc 扩展名的输出名称。

File.open('C:\Users\darkop\Desktop\final_output.doc','a') do |final|
  @files = Dir.glob("D:\text\*.txt")
  @files.each do |file|
    text = File.open(file, 'r').read.sub(/#$/?\z/, $/)
    text.each_line do |line|
      puts "File Name: #{file}"
      puts
      puts line
      final << line
      puts "=" * 20 
    end
  end
end

【讨论】:

  • Van Dijik : +1 指出我的错误。我做了进一步修改以获得上述格式:File.open('D:/output.doc','a') do |final| @files = Dir.glob("D:/text/*.txt") for file in @files final.puts "File Name: #{file}" final.puts text = File.open(file, 'r').read.sub(/#$/?\z/, $/) text.each_line do |line| final &lt;&lt; line end final.puts "=" * 70 end end 在这里感谢您的时间。
猜你喜欢
  • 2012-08-27
  • 1970-01-01
  • 2021-03-01
  • 2018-08-29
  • 2017-01-28
  • 2017-04-05
  • 2023-01-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多