read data line by line

  • Thread starter Krishna Vutukuru
  • Start date
K

Krishna Vutukuru

could anybody please give me an example of how to read data from a text
file line by line so that manipulations can be made on each and
everyline and copy those to other file?
 
J

James Edward Gray II

could anybody please give me an example of how to read data from a
text
file line by line so that manipulations can be made on each and
everyline and copy those to other file?

File.open("output.txt", "w") do |output|
File.foreach("input.txt") do |line|
# change line here...
output << line
end
end

Hope that helps.

James Edward Gray II
 
V

Vassilis Rizopoulos

James said:
File.open("output.txt", "w") do |output| File.foreach("input.txt") do
|line| # change line here... output << line end end

Hope that helps.

James Edward Gray II
As well as something like this

lines=File.readlines("filename")
lines.collect!{|l| do something with l and give it back}
File.open("output","w"){|f| f<<lines.join("\n")}

Pedantic, I know :)
V.-
 
J

James Edward Gray II

As well as something like this

lines=File.readlines("filename")
lines.collect!{|l| do something with l and give it back}
File.open("output","w"){|f| f<<lines.join("\n")}

Pedantic, I know :)

The problem with your solution is that it slurps all the data into
memory at once. For large data sets, this may not be an option.

My solution only reads one line at a time and thus is a lot more
memory friendly.

James Edward Gray II
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,239
Messages
2,571,200
Members
47,840
Latest member
Tiffany471

Latest Threads

Top