简体   繁体   English

当打印文件中的行时,Ruby控制台会覆盖行

[英]Ruby console overwrites line when printing out lines in a file

I have started learning Ruby and I have come across an annoying problem. 我已经开始学习Ruby,并且遇到了一个烦人的问题。 I have imported a text file into my program and I want to iterate over the lines in it and print them out to the screen. 我已将文本文件导入程序,我想遍历其中的行并将其打印到屏幕上。

When I do this, the console overwrites the last printed out line and writes the new one on top. 当我这样做时,控制台将覆盖最后打印出的行,并将新的写在最上面。 Why is this happening and how can I solve it? 为什么会发生这种情况,我该如何解决?

Here is my code: 这是我的代码:

passwords = File.open('C:\Users\Ryan\Desktop\pw.txt', 'r')
lines = passwords.gets

for line in lines
    puts line
end

Update: The loop is acting very strange. 更新:循环的行为很奇怪。 I put a sleep statement into it and all it did was sleep once then continue to output the lines. 我在其中添加了一条sleep语句,它所做的只是睡眠一次,然后继续输出行。 I would have expected it to sleep before outputting each line. 我本来希望它在输出每一行之前都处于休眠状态。 Example below: 下面的例子:

passwords.each do |line|
    sleep 1
    puts line.chomp
end

Update 2: I just created a new text file and typed some random stuff into it for testing and it works fine. 更新2:我刚刚创建了一个新的文本文件,并在其中输入了一些随机的东西进行测试,并且效果很好。 Looks like the original file had some bad characters/encoding which messed up the printing to the console. 看起来原始文件中包含一些错误的字符/编码,使打印到控制台的工作变得混乱。

Do you have an EOL (AKA end-of-line) problem? 您是否遇到EOL(又名“行尾”)问题? Try this: 尝试这个:

passwords = File.open('C:\Users\Ryan\Desktop\pw.txt', 'r')
lines = passwords.gets
lines.each { |line| puts line.chomp }
passwords.close

The chomp call will strip off any \\n , \\r , or \\r\\n line endings, then puts will append the native EOL. chomp调用将删除任何\\n\\r\\r\\n行尾,然后puts将附加本机EOL。

File.open('C:\Users\Ryan\Desktop\pw.txt') do |line|
  while not line.eof?
    puts line.readline.chomp
  end
end

or 要么

File.read("file").each { |line| puts line.chomp }

In the end I found out that the text file was the cause of my problem. 最后,我发现该文本文件是导致我出现问题的原因。 I created a new one with the same content and it started working how I intended. 我创建了一个内容相同的新书,它开始按我的预期工作。

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

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