You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取文件行后回退读取位置的逻辑错误求助

Fixing File Monitoring Loop: Stop Re-reading from the Start

Let's break down why your current code keeps re-reading the file from the beginning, then fix it to monitor new content correctly.

What's Wrong with Your Current Code?

  1. Reopening the File Every Loop: Your with open('file.txt', 'r') as fp sits inside the while True loop. Every iteration reopens the file fresh, resetting the file pointer to the start—so you always read the same lines over and over.
  2. Incorrect File Pointer Usage: You tried file.seek(-len(i),1) but used the wrong variable name (file instead of fp), and even if that worked, reopening the file would wipe out any progress you made with seek.
  3. Indentation & Logic Gaps: The else block is attached to the for loop (not the while), and you're missing an import for time.sleep().

Solution: Track Your Read Position

The core fix is to remember where you left off in the file between loop iterations. Here are two solid approaches:


Approach 1: Track Position with tell() and seek() (Safer for Dynamic Files)

This method opens the file each time (good if the file might be moved/renamed) but retains the last read position:

import time

def monitor_file(file_path):
    last_read_pos = 0  # Store where we stopped reading last time
    while True:
        try:
            with open(file_path, 'r') as fp:
                # Jump to the last position we finished reading
                fp.seek(last_read_pos)
                new_lines = fp.readlines()
                
                if new_lines:
                    for line in new_lines:
                        line = line.strip()
                        if not line:
                            continue  # Skip empty lines
                        
                        # Validate line format to avoid index errors
                        data = line.split()
                        if len(data) >= 6:
                            program = data[1]
                            user = data[3]
                            code = data[5]
                            total = program + user + code
                            print(total)
                    
                    # Update our position to the end of the newly read content
                    last_read_pos = fp.tell()
                else:
                    print("No new content—putting to sleep!")
                    time.sleep(5)
        
        except FileNotFoundError:
            print("File not found, waiting 5 seconds...")
            time.sleep(5)
        except Exception as e:
            print(f"Unexpected error: {str(e)}")
            time.sleep(5)

if __name__ == "__main__":
    monitor_file('file.txt')

Approach 2: Keep the File Open (More Efficient)

If the file won't be moved or deleted while your program runs, keeping it open avoids repeated opening/closing overhead:

import time

def monitor_file(file_path):
    fp = open(file_path, 'r')
    try:
        while True:
            line = fp.readline()
            if line:
                line = line.strip()
                if line:
                    data = line.split()
                    if len(data) >= 6:
                        program = data[1]
                        user = data[3]
                        code = data[5]
                        print(f"{program}{user}{code}")
            else:
                print("No new lines—sleeping!")
                time.sleep(5)
                
                # Handle case where file was truncated (e.g., cleared and rewritten)
                current_file_size = fp.seek(0, 2)  # Jump to end and get current size
                if current_file_size < fp.tell():
                    fp.seek(0)  # Reset to start if file got smaller
    except Exception as e:
        print(f"Error occurred: {str(e)}")
    finally:
        fp.close()  # Clean up the file handle when done

if __name__ == "__main__":
    monitor_file('file.txt')

Key Improvements

  • Position Tracking: Both methods ensure you only process new lines, not repeat existing content.
  • Error Handling: Added checks for missing files and unexpected issues to keep your program running reliably.
  • Format Validation: Prevents IndexError by verifying lines have enough elements before accessing split indices.

内容的提问来源于stack exchange,提问作者cma1941

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:33:08