简体   繁体   English

获取循环内文本文件的最后几行

[英]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. 我想在用户输入中获取txt文件的最后几行。 For example if get_number = 2 The last 3 lines are redundant. 例如,如果get_number = 2,则后3行是多余的。 I will get the 4th and 5th lines from at the end of text. 我将从文本末尾得到第4行和第5行。

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

if get_number = 3 如果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. get_number最多可以为9。

Finally, I will write this data to txt file. 最后,我将这些数据写入txt文件。

   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 ? 如何通过循环实现呢?

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])

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM