简体   繁体   English

Ruby读取文件行问题

[英]Ruby read file line issue

I'm trying to read a file into a string. 我正在尝试将文件读取为字符串。 For instance, I tried reading this file: 例如,我尝试读取此文件:

123456  
23456  
3456  
456  
56  
6

I tried: 我试过了:

contents = File.open("test.txt", "rb").read  
print contents

IO.foreach('test.txt') do |line|  
  print line  
end

File.open('test.txt', 'r').each_line do |line|
  print line
end     

but I seem to get a single line that will overwrite it's contents with each new line. 但我似乎只有一行可以用新行覆盖它的内容。 I get 666666 . 我得到666666

The issue has to be the fact that the file is using the CR line terminator (or your terminal is messed up and not responding to LF). 问题必须是该文件正在使用CR行终止符(或者您的终端混乱了,并且无法响应LF)。 print does not go into the new line by default (you should use puts if that's what you want), and each_line does not strip the line terminator. 默认情况下, print不会进入新行(如果需要,请使用puts ),并且each_line不会each_line行终止符。 So what happens is, print "123456\\r " prints out 123456 and then returns the cursor to the start of the line, without moving to the next line (so the cursor is on 1 . Then when you print "23456\\r" , it will overwrite the first five characters and again come back to the start, the current state being 234566 ... In the end, 566666 will get overwritten by "6\\r" for the final 666666 . 所以发生的是, print "123456\\r ”会打印出123456 ,然后将光标返回到该行的开头,而不移动到下一行(因此光标在1 。然后,当您print "23456\\r" ,它将覆盖前五个字符,然后再次返回到开头,当前状态为234566 ...最终, 566666将被"6\\r"覆盖,成为最后的666666

Why not try the simple solution 为什么不尝试简单的解决方案

# ruby sample code.
# process every line in a text file with ruby (version 1).
file='test.txt'
File.readlines(file).each do |line|
  puts line
end

Second approach 第二种方法

# ruby sample code.
# process every line in a text file with ruby (version 2).
file='test.txt'
f = File.open(file, "r")
f.each_line { |line|
  puts line
}
f.close

Answer Source 答案来源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM