File Append Problem

Hello,

I am reading a csv file (File1) and putting its content into a string,
then I append that string in another csv file (file2) that has some data
in it already. Now I do not want to overwrite the data in file2 so i’ve
opened file2 in append mode, and the string from file1 is appended to
file2, but, I lose some characters in the first line of my string, it
looks almost like the first line of my string from file1 is trying to
overwrite the last line in file2 but it doesn’t. My string just loses
the same amount of characters of the number of characters from my last
line that was already in file2. Long story short, It won’t append
correctly.

Here is the code:

File.new(rightfile,“w”)

fileNew = File.open(rightfile,“w”)
fileNew.puts
‘“email”,“source”,“ip”,“data_timestamp_proper”,“firstname”,“lastname”’

str = IO.read(outfile)

fileAppend = File.open(rightfile,“a”)
fileAppend.puts str

On 2007-07-21 04:10:22 +0900 (Sat, Jul), Matthew L. wrote:

line that was already in file2. Long story short, It won’t append
str = IO.read(outfile)

fileAppend = File.open(rightfile,“a”)
fileAppend.puts str

Have you debugged what is the contents of str ?
Maybe the problem is not in appending but reading?

If this is the exact code you run, then you are opening the file three
times, without closing it or flushing its buffers:

First: File.new(rightfile,‘w’)
Second: File.open(rightfile,‘w’)
Third: File.open(rightfile,‘a’)

I suggest something like:

File.open( rightfile, ‘w’) do |f|
f.puts ‘“email”,“source”…’
end

str = IO.read(outfile)

File.open( rightfile, ‘a’) do |f|
f.puts str
end

but it may be shortened to just:

File.open( rightfile, ‘w’ ) do |right|
right.puts ‘“email”,"…"’
str = IO.read( outfile )
right.puts str
end

File.open( rightfile, ‘w’ ) do |right|
right.puts ‘“email”,"…"’
str = IO.read( outfile )
right.puts str
end

Oh i see now, I have got to stop programming so structured. Thanks alot!