How do I remove lines of data in the middle of a text file with Ruby -
i know how write file, , read file, don't know how modify file besides reading entire file memory, manipulating it, , rewriting entire file. large files isn't productive.
i don't know difference between append , write.
e.g.
if have file containing:
person1,will,23 person2,richard,32 person3,mike,44
how able delete line containing person2?
you can delete line in several ways:
simulate deletion. is, overwrite line's content spaces. later, when read , process file, ignore such empty lines.
pros: easy , fast. cons: it's not real deletion of data (file doesn't shrink) , need more work when reading/processing file.
code:
f = file.new(filename, 'r+') f.each |line| if should_be_deleted(line) # seek beginning of line. f.seek(-line.length, io::seek_cur) # overwrite line spaces , add newline char f.write(' ' * (line.length - 1)) f.write("\n") end end f.close file.new(filename).each {|line| p line } # >> "person1,will,23\n" # >> " \n" # >> "person3,mike,44\n"
do real deletion. means line no longer exist. have read next line , overwrite current line it. repeat following lines until end of file reached. seems error prone task (lines of different lengths, etc), here's error-free alternative: open temp file, write lines (but not including) line want delete, skip line want delete, write rest temp file. delete original file , rename temporary 1 use name. done.
while technically total rewrite of file, differ asked. file doesn't need loaded memory. need 1 line @ time. ruby provides method this: io#each_line.
pros: no assumptions. lines deleted. reading code needs not altered. cons: lots more work when deleting line (not code, io/cpu time).
there snippet illustrates approach in @azgult's answer.
Comments
Post a Comment