Reading external files
-
chosen_file is a external file. I would like to search the chosen_file line by line for "XXXX", then save the next line in the data array. How do I increment the read file pointer to the next line?
aFile = File.open(chosen_file, "r") Data = [] #Search each line for "XXXX" aFile.each_line do |line| If line == "XXXX" #if found #How do I get next_line, to save to Data Data.push next_line end end aFile.close -
aFile.read_line? -
The following generates error message:
undefined method ‘read_line’ for #<File:C:TEST.DAT>aFile = File.open(chosen_file, "r") aFile.each_line do |line| aFile.read_line end aFile.close -
array_of_lines=IO.readlines(chosen_file)Will let you do what you want, line by line or not, no pointer, no nothing

-
Didier, Thanks. I will try that when I go to the office later today

-
Well, that created an array of the whole file. Can I just get the next (n) line? I can do it with a counter as attached, but the code gets complicated when searching for many different line descriptions.
aFile = File.open(chosen_file, "r") SaveIt = [] count = 0 line_location = -1 aFile.each_line do |line| count = count + 1 if line == "xxxx" #calculate the location of the next line line_location = count + 1 #test if location and current line match else if line_location == count SaveIt.push line end end end aFile.close -
.../... array_of_lines=IO.readlines(chosen_file) saveIt = [] skipNext=false 0.upto(array_of_lines.length-1) { |i| if line[i] == "xxxx" and !skipNext saveIt.push(array_of_lines[i+1]) skipNext=true else skipNext=false end } .../... -
:-0....now I get it, thanks.
Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better 💗
Register LoginAdvertisement