ruby - Is there a way to delete a line in a text file if it matches a specific text? -
my text file contains email/password list set accounts. once i've used email , password combo erase form text file.
my text file looks this:
email,pass email,pass etc..
once i've used e/p combo delete file:
file.open("yahoo_accounts.txt") |email| email.each |item| email, password = item.chomp.split(',') emails << email passwords << password emails.zip(passwords) { |name, pass| browser = watir::browser.new :ff #using email , pass file.open("yahoo_accounts.txt", "w") |out_file| file.foreach("yahoo_accounts.txt","r") |line| out_file.puts line unless line == '#{name},#{pass}' end end browser.close end end
the problem occurs when try delete them file. "browser.rb:382:in `assert_exists': browser closed (watir::exception::error)", might browser closing.
if e/p's extracted (meaning there nothing delete) in beginning, how can loop keep going, instead of ending in error after first zip loop?
if file not huge, can read array, modify array , write array file, overwriting previous contents.
code
def remove_lines(fname, user_name, password) io.write(fname, io.read(fname).gsub(/^#{user_name},#{password}\n/, '')) end
example
let's create data:
text =<<_ bubba,boar henrietta,vespa luigi,pink bubba,boar luigi,mauve _ #=> "bubba,boar\nhenrietta,vespa\nluigi,pink\nbubba,boar\nluigi,mauve\n"
and write file:
fname = "tmp" io.write(fname, text) #=> 61
we can confirm we've written file:
io.read(fname) #=> "bubba,boar\nhenrietta,vespa\nluigi,pink\nbubba,boar\nluigi,mauve\n"
now remove lines user_name/password #=> bubba/boar
:
remove_lines(fname, "bubba", "boar") #=> 39
let's confirm worked examining fname
:
io.read(fname) #=> "henrietta,vespa\nluigi,pink\nluigi,mauve\n"
postscript
if goes wrong while writing array file, may lose both old file , new file. reason, practice write array temporary file, delete original file, rename temporary file name of original file.
Comments
Post a Comment