如何删除Ruby中的最后一行文件? [英] How to delete last line of file in Ruby?

查看:157
本文介绍了如何删除Ruby中的最后一行文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在访问一个文件,在追加到文件之前,我想从文件中删除最后一行。有没有什么有效的方式来做到这一点在Ruby?



这是我用来访问文件:

  file = File.new(imcs2.xml,a)


<假设你想删除整个文件的最后一行,你可以使用这个方法来定位最后一行的开始,然后从那里开始写:

p>

  last_line = 0 
file = File.open(filename,'r +')
file.each {last_line = file.pos除非file.eof? }

file.seek(last_line,IO :: SEEK_SET)
#在这里写你自己的东西
file.close


I am accessing a file, and before I append to it, I want to delete the last line from the file. Is there any efficient way of doing this in Ruby?

This is what I am using to access the file:

file = File.new("imcs2.xml", "a")

解决方案

Assuming you want to remove the entire last line of the file, you can use this method which locates the start of the last line and begins writing from there:

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

这篇关于如何删除Ruby中的最后一行文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆