如何解决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
Loggerclass and reassigningsys.stdoutevery single loop iteration
Each time the loop runs, you create a newLoggerinstance and set it assys.stdout. The problem? The new logger'sterminalattribute points to the previoussys.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
EachLoggerinstance 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
Loggerclass 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()andclose()methods: These ensure messages are written immediately (no buffering surprises) and clean up the file handle when you stop the program. Thetry-finallyblock guarantees the logger gets closed even if you hit Ctrl+C to stop the loop. - Added
import sys: Your original code was usingsysbut 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
withstatements 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
相关产品推荐
相关产品推荐

