Posted By

chrisaiv on 06/04/08



Versions (?)

Who likes this?

1 person have marked this snippet as a favorite


Open a text file and re-write its contents into a new text file

 / Published in: Ruby

Basic example of how to open a text file and print them (including line-numbers) into a new text file

  1. counter = 1
  2. old_file ="./Car.txt", "r")
  3. new_file ="./NewCar.txt", "w")
  4. while( line = old_file.gets )
  5. new_file.puts "#{counter}: #{line}"
  6. counter = counter + 1
  7. end
  8. new_file.close

Report this snippet  


RSS Icon Subscribe to comments
Posted By: c00lryguy on June 13, 2008

dude.. why not:"./lol.txt", "r") { |file|"./#{ File.basename(file.path, ".txt") }_new.txt", "w+").puts( }

Or:"./lol.txt", "r") { |fileold| filenewfilename = "#{ File.basename(file.path, ".txt") }new.txt" #append "new" to the end of the filename filenew =, "w+") file_new.puts( }

Posted By: c00lryguy on June 13, 2008

Gah, the site messed up the second one. but you get the point. Ruby is stronger than you think

Posted By: chrisaiv on June 20, 2008

Right on "c00lryguy", thanks for the post. You're right too, Ruby is one bad ass language.

You need to login to post a comment.