blufur wrote:
A couple quick questions:
how can my ruby program tell me how many lines are in a text file?
how can i have my ruby program edit the last line of a text file (not
add another line at the end, but get and then change the line at the
end).
#Read the file and count the lines:
File.open("data.txt", "w") do |file|
(1..25).each {|num| file.puts("line #{num}")}
end
count = 0
File.open("data.txt") do |file|
file.each {count += 1}
end
puts count #25
#To change the last line of a file that isn't
#extremely large:
lines_arr = IO.readlines("data.txt")
lines_arr[-1] = "hello world\n"
File.open("temp.txt", "w") do |file|
lines_arr.each do |line|
file.write(line)
end
end
File.delete("data.txt")
File.rename("temp.txt", "data.txt")
#Display the result:
File.open("data.txt") do |file|
file.each do |line|
print line
end
end
--output--
line 1
line 2
line 3
...
...
line 23
line 24
hello world
For extremely large files on the order of 1-2GB, you can try something
like this:
last_line = nil
temp_file = File.new("temp.txt", "w")
File.open("data.txt") do |file|
file.each do |line|
if last_line
temp_file.write(last_line)
end
last_line = line
end
end
last_line = "hello world\n"
temp_file.write(last_line)
temp_file.close()
#Delete and rename as above
···
--
Posted via http://www.ruby-forum.com/\.