Update a particular Field in a csv file

Hi Friends,

I am having a role.csv file as like

emp_id,dep_id,role,salary,accepted
1,1,SSE,10000,YES
2,2,SSE,11000,NO
3,1,SSE,9000,YES
4,2,SSE,12000,YES
5,1,SSE,8000,NO

Now, I need to update this role.csv file as like below

emp_id,dep_id,role,salary,accepted
1,1,SSE,10000,NO
2,2,SSE,11000,YES
3,1,SSE,9000,NO
4,2,SSE,12000,YES
5,1,SSE,8000,NO

I tried with FasterCSV and CSV class none of them provide a full access
mode to edit this CSV file.

I have a sample code but thats not looking very effective (but working
fine)

Note : CSV file is a sample one (Don’t think Logic in that)

def update_csv_report( emp_id, dep_id, is_accepted )
new_rows = Array.new
CSV.open(‘role.csv’, ‘r’) do |row|
if (row[0] == emp_id && row[1] == dep_id)
new_rows << [row[0], row[1], row[2], row[3], is_accepted]
else
new_rows << [row[0], row[1], row[2], row[3], row[4]]
end
end

CSV.open('role.csv', 'w') do |writer|
    new_rows.each do |row|
        writer << row
    end
end

end

I am facing 2 issues in this

  1. For every updating the CSV file, I am rewriting the whole CSV file.
    That not a teddy way to do it.
  2. I am opening the file first time for reading and 2nd time for
    writing. That is also not convincing me.

Please help me in this. How to Improve this code. Main motive is to
updated a particular field instead of rewriting the whole CSV file.

Cheers,
Antony Prabhu N.

Probably too late to help the OP, but in case anyone finds this in an
archive …

On Thu, 15 Apr 2010 08:35:40 -0500, Antony N.
[email protected] wrote in
[email protected]:

Now, I need to update this role.csv file as like below

emp_id,dep_id,role,salary,accepted
1,1,SSE,10000,NO
2,2,SSE,11000,YES
3,1,SSE,9000,NO
4,2,SSE,12000,YES
5,1,SSE,8000,NO

[snip code]

I am facing 2 issues in this

  1. For every updating the CSV file, I am rewriting the whole CSV file.
    That not a teddy way to do it.
  2. I am opening the file first time for reading and 2nd time for
    writing. That is also not convincing me.

The problem is that you’re dealing with a single file, not a database.
In order to alter the contents of that file, you’re going to have to
read the entire thing into memory, alter it, and then write it back
out to disk. That’s just the way it works.

You could always move the data into a database, which would allow you
to update only an individual record.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs