Removing file content after a specific line in ruby

Probably a simple question, but do I need to delete the contents of a file after a certain line number? So I will not save the first, say 5 lines, and delete the rest of the file content. I've been looking for a while and can't find a way to do this, I'm an iOS developer, so Ruby is not a language that I'm very familiar with.

+3


source to share


2 answers


I am not aware of any methods of deleting from a file, so I first thought I needed to read the file and then write to it. Something like that:

path = '/path/to/thefile'
start_line = 0
end_line = 4
File.write(path, File.readlines(path)[start_line..end_line].join)

      



File#readlines

reads the file and returns an array of strings, where each element is one line of the file. Then you can use the indexed operator on the strings you need

It won't be very efficient for storing large files, so you can optimize if you do something.

+2


source


This is called truncate . The truncate method needs a byte position after which everything is truncated - and the method File.pos

provides just that:

File.open("test.csv", "r+") do |f|
  f.each_line.take(5)
  f.truncate( f.pos )
end

      



The "r +" mode from File.open is read and written without truncating existing files to zero size, eg "w +".

The form of the File.open block ensures that the file is closed when the block ends.

+5


source







All Articles