Posted By

chrisaiv on 06/04/08


Tagged

ruby


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

webstic


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 = File.open("./Car.txt", "r")
  3. new_file = File.new("./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  

Comments

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

dude.. why not:

File.open("./lol.txt", "r") { |file| File.new("./#{ File.basename(file.path, ".txt") }_new.txt", "w+").puts(file.read) }

Or:

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

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.