Hi guys?
How can i append another columns with header name into the CSV?
Example:
My file csv:
col1 col2
How can i add col3?
Thank you
Hi guys?
How can i append another columns with header name into the CSV?
Example:
My file csv:
col1 col2
How can i add col3?
Thank you
READ IT LINE BY LINE , APPEND A COLUMN ON EACH LINE, AND REWRITE LINE
name=“Colname”
File.open(“onput.csv”) {|fin|
File.open(“output.csv”,“w”) {|fout|
while str=fin.gets
fout.puts str+";#{name}"
name=“data…”
end
}
}
hi Regis d’Aubarede
I find the file is empty once I have executed your program. I used text
files.
name=“Colname”
File.open(“one.txt”) {|fin|
File.open(“one.txt”,“w+”) {|fout|
while str=fin.gets
fout.puts str+";#{name}"
name=“data…”
end
}
}
Raja Gopalan wrote in post #1176911:
hi Regis d’Aubarede
I find the file is empty once I have executed your program. I used text
files.
This work (supposed ‘;’ is field separator in your csv):
name=“Colname”
File.open(“one.txt”) {|fin|
File.open(“two.txt”,“w”) {|fout|
while str=fin.gets
fout.puts str.chomp+";#{name}"
name=“data…”
end
}
}
The out filename must be different than the input
You can’t read and write a text file in same time.
So,another way is to read all content of file,
transform the data, en rewrite:
content=File.readlines(“one.txt”)
name=“Colname”
File.open(“one.txt”,“w”) {|fout|
content.each {|line|
fout.puts line.chomp+";#{name}"
name=“default-data…”
}
}
Regis d’Aubarede wrote in post #1176935:
or this one perhaps simpler:
content=File.readlines(“one.txt”)
name=“Colname”
content.map! {|line| x="#{line.chomp};#{name}" ; name=‘default’ ; x}
File.write(“one.txt”,content.join("\n"))
hi Regis d’Aubarede
Thank you very much, your explanation is very clear!
Thank you very much evrybody
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs