I know how to write to a file, and read from a file, but I don't know how to modify a file besides reading the entire file into memory, manipulating it, and rewriting the entire file. For large files this isn't very productive.
I don't really know the difference between append and write.
E.g.
If I have a file containing:
Person1,will,23
Person2,Richard,32
Person3,Mike,44
How would I be able just to delete line containing Person2?
To delete a file you need to use #delete command of the File class. You can use ruby's "fileutils" module to achieve deleting folders/directories. Let us say that I have to delete a folder at C:\Users\adhithya\desktop\ called "demo" that needs to be deleted.
You could open the file and read it line by line, appending lines you want to keep to a new file. This allows you the most control over which lines are kept, without destroying the original file.
File.open('output_file_path', 'w') do |output| # 'w' for a new file, 'a' append to existing
File.open('input_file_path', 'r') do |input|
line = input.readline
if keep_line(line) # logic here to determine if the line should be kept
output.write(line)
end
end
end
If you know the position of the beginning and end of the chunk you want to remove, you can open the file, read to the start, then seek to the end and continue reading.
Look up parameters to the read method, and read about seeking here:
http://ruby-doc.org/core-2.0/IO.html#method-i-read
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With