Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read the second line in a document.txt and then make a loop that reads line +1 in this document

Tags:

ruby

watir

My bot reads emails one by one from a document.txt file and after login with this email the bot outputs the comments that I have in another file.

I have reached the point that the bot reads the emails but I want that a specific account makes a specific and not a repeated comment.

So I have in mind the solution of reading a specific line from the comments file.

For example account 1 reads and puts line 1 of the comments file. I want to know how can I read the second line from a comments file.

This is the code part when I read comments one by one but I want to read for example line two or three!

file = 'comments.txt'
File.readlines(file).each do |line|
    comment = ["#{line}"] 
    comment.each { |val| 
        comment = ["#{val}"] 
}
end
like image 665
Astrit Shuli Avatar asked Aug 19 '19 15:08

Astrit Shuli


People also ask

How to read text files line by line in Python?

Method 1: Read a File Line by Line using readlines() readlines() is used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines.

How to read file one line at a time in Python?

The readline() method helps to read just one line at a time, and it returns the first line from the file given. We will make use of readline() to read all the lines from the file given. To read all the lines from a given file, you can make use of Python readlines() function.

How do you start a second line in Python?

In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line. Essentially the occurrence of the “\n” indicates that the line ends here and the remaining characters would be displayed in a new line.


2 Answers

File.readlines returns array. So you can do everything you want

lines = []

File.readlines(path_to_file, chomp: true).each.with_index(1) do |line, line_number|
  lines << (line_number == 2 ? 'Special line' : line)
end
like image 84
mechnicov Avatar answered Oct 02 '22 10:10

mechnicov


Try the below.

# set the line number to read
line_number = 2 # <== Reading 2nd line
comment = IO.readlines('comments.txt')[line_number-1]
like image 33
supputuri Avatar answered Oct 02 '22 11:10

supputuri