我正在访问一个文件,在向其追加内容之前,我想删除文件中的最后一行。在Ruby中有没有高效的方法来实现这个功能?
以下是我用来访问该文件的代码:
file = File.new("imcs2.xml", "a")
last_line = 0
file = File.open(filename, 'r+')
file.each { last_line = file.pos unless file.eof? }
file.seek(last_line, IO::SEEK_SET)
#Write your own stuff here
file.close
最简单的方法就是读取整个文件,删除末尾的 '\n',然后用自己的内容重新写入:
filename = "imcs2.xml"
content = File.open(filename, "rb") { |io| io.read }
File.open(filename, "wb") { |io|
io.print content.chomp
io.print "yourstuff" # Your Stuff Goes Here
}
或者,如果有的话,只需通过 io.seek() 向后移动到最后一个换行符:
filename = "imcs2.xml"
File.open(filename, "a") { |io|
io.seek(-1, IO::SEEK_CUR) # -1 for Linux, -2 for Windows: \n or \r\n
io.print "yourstuff" # Your Stuff Goes Here
}