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

如何解决Python中stdout输出至TXT文件的重复日志数据问题

Why Your Python Code Is Generating Duplicate Data in the TXT File

Hey there! As a fellow Python learner, I totally get how frustrating it is when your code starts spamming duplicate data out of nowhere. Let's break down what's happening in your code and fix it step by step.

The Root Cause of Duplicate Data

Looking at your loop, here are two big issues that are causing the duplicate flood:

  • You're redefining the Logger class and reassigning sys.stdout every single loop iteration
    Each time the loop runs, you create a new Logger instance and set it as sys.stdout. The problem? The new logger's terminal attribute points to the previous sys.stdout (which was already a logger from the last loop). So every print now gets passed through multiple logger layers—each layer writes the same message to your file, leading to more and more duplicates each time the loop runs.
  • You're opening the file multiple times without closing it
    Each Logger instance opens "mylogfile.txt" in append mode, but you never close these file handles. This not only causes duplicate writes but also wastes system resources.

Fixed Code Example

Let's rewrite your code to fix these issues. I'll add comments to explain each change:

import logging
import sys  # Don't forget to import sys! Your original code was missing this
from time import sleep

# Define the Logger class ONCE, outside the loop—no need to recreate it every time
class Logger(object):
    def __init__(self, filename="Default.log"):
        self.terminal = sys.stdout  # Save the original stdout once
        self.log = open(filename, "a")
    
    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)
    
    # Add flush method to ensure messages are written immediately
    def flush(self):
        self.terminal.flush()
        self.log.flush()
    
    # Add close method to clean up the file handle when done
    def close(self):
        self.log.close()
        sys.stdout = self.terminal  # Restore original stdout

# Initialize the logger ONCE, before the loop
sys.stdout = Logger("mylogfile.txt")

x = 0
try:
    while True:
        x += 1
        print(f"you gotta be very careful {x}")  # Using f-string for cleaner formatting
        print(f"x, {x:.2f}")
        sleep(0.25)
finally:
    # Make sure we close the logger and restore stdout even if the loop stops unexpectedly
    sys.stdout.close()

Key Changes Explained

  • Moved Logger class definition outside the loop: Classes only need to be defined once in Python. Redefining them every loop is unnecessary and causes unexpected behavior.
  • Initialized the logger once before the loop: This way, we only have one logger handling sys.stdout, so each print message gets written to the file exactly once.
  • Added flush() and close() methods: These ensure messages are written immediately (no buffering surprises) and clean up the file handle when you stop the program. The try-finally block guarantees the logger gets closed even if you hit Ctrl+C to stop the loop.
  • Added import sys: Your original code was using sys but didn't import it—this would have caused an error!

Extra Tips for New Python Learners

  • Always test small parts of your code first: If you're confused about why something is happening, try running just the logger part without the loop to see how it behaves.
  • When working with files directly, use with statements whenever possible (it automatically closes the file for you):
    with open("mylogfile.txt", "a") as f:
        f.write("Hello, world!\n")
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:07:14