0

I have a large csv. I want to delete the first line of the file. How is this done? I don't want to copy every line into an array and rewrite them for the previous index and delete the first. There must be a better way. (maybe with fastercsv? how?)

1
  • Not a Rails specific question. Commented Feb 16, 2012 at 12:03

4 Answers 4

2

If you don't mind shelling out to a command line, it is particularly efficient:

system("tail -n +2 #{input} > #{output}")
Sign up to request clarification or add additional context in comments.

Comments

1

Something like :

source=File::open("source","r")
dest=File::open("dest","w")
source.each_line do |line|
  next if f.lineno == 1
  dest.write(line)
end
source.close
dest.close

3 Comments

Wrong, whole source file is read into memory questioner would like to avoid.
My bad, I read the question too quickly. Here's a modified version reading the file line by line
You are not closing the file handles. Either close them explicitly or use the block form of File.open.
0

Copy the file to another file, omitting the line(s) you want deleted. You don't have to load the file into an array, just read and write line by line within the same loop.

Comments

0

You mean like this?

source_path = 'liner.txt'

open source_path do |input|
  input.gets

  open "#{source_path}.header_removed", 'w' do |output|
    input.each do |line|
      output << line
    end
  end
end

But, this code require simple format for CSV

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.