Read previous line in a file python

前端 未结 3 689
一个人的身影
一个人的身影 2021-01-04 16:13

I need to get the value of the previous line in a file and compare it with the current line as I\'m iterating through the file. The file is HUGE so I can\'t read it whole or

3条回答
  •  暖寄归人
    2021-01-04 17:14

    @Lim, here's how I would write it (reply to the comments)

    def do_stuff_with_two_lines(previous_line, current_line):
        print "--------------"
        print previous_line
        print current_line
    
    my_file = open('my_file.txt', 'r')
    
    if my_file:
        current_line = my_file.readline()
    
    for line in my_file:
    
        previous_line = current_line
        current_line = line
    
        do_stuff_with_two_lines(previous_line, current_line)
    

提交回复
热议问题