pylearner
pylearner

Reputation: 537

Get the last lines of a text file within loop

get_number = int(raw_input("How many bootloogs do you wish to upload? "))

I would like get the last lines of a txt file on user inputs. For example if get_number = 2 The last 3 lines are redundant. I will get the 4th and 5th lines from at the end of text.

  first_log = file(file_success, 'r').readlines()[-4]
  second_log = file(file_success, 'r').readlines()[-5]

if get_number = 3

Then, I will need to add another line.

third_log = file(file_success, 'r').readlines()[-6]

get_number can be up to 9.

Finally, I will write this data to txt file.

   with open(logs_file, "a+") as f:
                f.write("===========================================")
                f.write(ip)
                f.write("===========================================\r\n")
                f.write(first_log)
                f.write(second_log)
                f.close()

How can I achieve that with loops ?

Upvotes: 0

Views: 56

Answers (2)

zwer
zwer

Reputation: 25789

If your log file can fit whole into memory, you can just slice and reverse the lines:

log_lines = file(file_success, 'r').readlines()

with open(logs_file, "a+") as f:
    f.write("===========================================")
    f.write(ip)
    f.write("===========================================\r\n")
    f.write("".join(log_lines[-4:-4-get_number:-1]))
    f.close()

Upvotes: 0

Haris
Haris

Reputation: 12270

You can use something like this

get_number = int(raw_input("How many bootloogs do you wish to upload? "))
all_lines = file(file_success, 'r').readlines()

extracted_lines = []
for i in range(get_number):
    extracted_lines.append(all_lines[-4 - i])

Upvotes: 1

Related Questions