如何在Ruby中编写文件后读取文件

时间:2017-08-03 18:50:18

标签: ruby

当我运行以下代码取自Learn Ruby the Hard Way Course Exercise 16

filename = ARGV.first
target = open(filename, 'w+')

puts "Now I'm going to ask you for three lines."

print "line 1: "
line1 = $stdin.gets.chomp
print "line 2: "
line2 = $stdin.gets.chomp
print "line 3: "
line3 = $stdin.gets.chomp

puts "I'm going to write these to the file."

target.write(line1 + "\n" + line2 + "\n" + line3)

puts "And now I'm going to print the file to prove I have altered it."
puts target.read

puts "And finally, we close it."
target.close

即使文本文件发生了变化,行puts target.read也不会打印三个输入行。

我尝试在调用open方法之前更改open方法使用的模式并添加新的read方法。使用相同的脚本创建一个单独的程序来读取和打印文本文件按预期工作。

如何阅读我刚刚写的文件?当我在同一个程序中编写和阅读时,为什么它不起作用?

2 个答案:

答案 0 :(得分:3)

  

当我在同一个程序中编写和阅读时,为什么它不起作用

答案是,当您写入文件时,您的IO流将设置为您编写的结尾。当你阅读时,它会从这一点继续。在这种情况下,写完后,您已到达文件末尾,没有其他内容可以“读取”。您可以使用IO#rewind重新开始并打印出刚刚通过IO Stream写入的内容。

filename = 'Test.txt'
target = open(filename, 'w+')

text  = '12345'
target.write(text) # target points to EOF
# Note that if you print target.write(), it will tell you the 'index' of where the IO stream is pointing. In this case 5 characters into the file.

puts "And now I'm going to rewind the file"
puts target.rewind # go back to the beginning of the file.
# => 0
puts "And now I'm going to print the file to prove I have rewound it."
puts target.read # read the file, target now points to EOF.
# => '12345'


target.close

答案 1 :(得分:-2)

File.open("my/file/path", "r") do |f|
  f.each_line do |line|
    puts line
  end
end

文件在块结束时自动关闭 如上所述,也可以显式关闭文件(传递一个块打开为你关闭它):

f = File.open("my/file/path", "r")
f.each_line do |line|
  puts line
end
f.close

感谢:https://stackoverflow.com/a/5545284/8328756