文件的所有行都在彼此打印

All lines of a file are printing over each other

我正在尝试将文件的内容打印到终端。当我 运行 脚本时,它会将所有行打印在彼此之上,所以我看到了整个最后一行,其他行的最后一位,等等。我尝试从 Powershell 和 cmd 执行,结果相同.这是我 运行ning...

的代码
File.open("test.txt", "r") {|file| puts file.read}

这是文件的内容...

First line......1.

Second line...2

Third line.3

结果如下...

PS C:\Users\Alynn\rthw> ruby ex19.rb test.txt

T h i r d l i n e . 3 . . 2 . . . 1 .

我找遍了,也找不到任何理由。

它对我有用。你应该检查你的 txt 文件上是否有 \n。

我复制了你的例子,然后 运行 在我的 irb

2.2.1 :006 > File.open("lines.txt", "r") {|file| puts file.read}
    First line......1.

    Second line...2

    Third line.3
 => nil 

无论如何,这个代码应该更适合你

2.2.1 :007 > puts File.read("lines.txt")
    First line......1.

    Second line...2

    Third line.3
 => nil 

您的文本文件使用 Mac OS (CR / '\r') 而不是 Unix (LF / '\n') 或 Windows (CRLF / '\r\n') 换行符。在 Windows(和大多数其他操作系统)上,Carriage Return 字符将设备位置设置为当前行的开头.这就是为什么你的输出被下一个输出覆盖的原因。

这取决于您的文本编辑器如何更改文本文件的换行符/行结尾。然而,它也可以用一些 Ruby 代码来完成:

IO.write('test_fixed.txt', IO.read('test.txt', newline: :universal))

改为传递 newline: :universal to IO.read causes non-Unix newlines to be converted to Unix (or universal as Ruby calls them) newlines. IO.write then converts the Unix newline to native (Windows) newlines. If you don't want that pass newline: :universal to it too or simply use IO.binwrite

如果您不想编辑文本文件但仍希望获得预期的输出,它也可以与您的代码一起使用:

File.open("test.txt", "r", newline: :universal) {|file| puts file.read}

我想通了,cremno 的想法是对的。我正在读取的文本文件以某种方式被编码为 "UCS-2 Big Endian",Notepad++ 在右下角将其称为 "Mac"。当我将原始文本文件转换为 ANSI 时,它解决了问题,这可能是 Horacio Branciforte 无法复制问题的原因。

我通过使用 IO.open 方法中的编码标签解决了这个问题。感谢您的帮助!