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
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.
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.
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.
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
Try the below.
# set the line number to read
line_number = 2 # <== Reading 2nd line
comment = IO.readlines('comments.txt')[line_number-1]
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