Ruby: Open a text file and re-write its contents into a new text file
Basic example of how to open a text file and print them (including line-numbers) into a new text file.
Example 1 - Long-hand
counter = 1
old_file = File.open("./Car.txt", "r")
new_file = File.new("./NewCar.txt", "w")
while( line = old_file.gets )
new_file.puts "#{counter}: #{line}"
counter = counter + 1
end
new_file.close
Example 2 - Short-hand
File.open("./lol.txt", "r") {
|file| File.new("./#{ File.basename(file.path, ".txt") }_new.txt", "w+").puts(file.read)
}
Example 3
# append "new" to the end of the filename
File.open("./lol.txt", "r") { |fileold| filenewfilename = "#{ File.basename(file.path, ".txt") }new.txt"
filenew = File.new(filenewfilename, "w+") file_new.puts(file.read) }