我在从Windows机器上构建文本文件时遇到问题,无法在Linux环境中读取。
def test
my_file = Tempfile.new('filetemp.txt')
my_file.print "This is on the first line"
my_file.print "\x0A"
my_file.print "This is on the second line"
my_file.close
FileUtils.mv(my_file.path, "C:/Users/me/Desktop/Folder/test.usr")
end
0A
是换行符的ASCII码,但是当我在Notepad ++中打开生成的文件时,我发现它在行尾有附加CR 和 LF。
如何将仅换行符添加为换行符?
答案 0 :(得分:3)
尝试将输出分隔符$\
设置为\n
。
def test
$\ = "\n"
my_file = Tempfile.new('filetemp.txt')
my_file.print "This is on the first line"
my_file.print "This is on the second line"
my_file.close
FileUtils.mv(my_file.path, "C:/Users/me/Desktop/Folder/test.usr")
end
或者您应该能够使用不会添加输出分隔符的#write
def test
my_file = Tempfile.new('filetemp.txt')
my_file.write "This is on the first line"
my_file.write "\x0A"
my_file.write "This is on the second line"
my_file.close
FileUtils.mv(my_file.path, "C:/Users/me/Desktop/Folder/test.usr")
end
答案 1 :(得分:1)
以二进制模式打开文件会导致Ruby''抑制EOL< - > Windows上的CRLF转换'(请参阅here)。
问题在于Tempfiles are automatically opened in w+
mode。在创建Tempfile时我找不到改变它的方法。
答案是使用binmode
创建后更改它:
def test
my_file = Tempfile.new('filetemp.txt')
my_file.binmode
my_file.print "This is on the first line"
my_file.print "\x0A" # \n now also works as a newline character
my_file.print "This is on the second line"
my_file.close
FileUtils.mv(my_file.path, "C:/Users/me/Desktop/Folder/test.usr")
end