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

求助:Python实现每小时写入文件24小时后自动新建文件的问题

Fixing Combined 24-Hour File Rotation + Hourly Writes in Python

Hey there! Let's figure out why merging your hourly file write and 24-hour file rotation logic is breaking, and how to fix it. First, let's cover the most common issues that pop up when combining these two behaviors:

Common Pitfalls

  • Unclosed File Handles: If you keep a file open for 24 hours straight and don't properly close it before switching to a new file, you might get write errors, resource leaks, or corrupted data.
  • Inaccurate Time Tracking: Using simple counters (like "count 24 hourly loops") can drift over time due to write delays or sleep inaccuracies, leading to premature or missed file rotations.
  • Conflicting Loop Logic: When merging two separate loops into one, it's easy to create nested loops that block each other or skip critical steps.

Working Combined Implementation

Here's a clean, integrated script that handles hourly writes and automatic file rotation after 24 hours, with none of the standalone issues:

import datetime
import time

def setup_new_file():
    # Create a new file with a timestamp in the name for clarity
    timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    return open(f"hourly_log_{timestamp}.txt", "a")

def main():
    # Initialize first file and track rotation start time
    current_file = setup_new_file()
    rotation_start = datetime.datetime.now()
    
    try:
        while True:
            # Get current time for write and rotation check
            now = datetime.datetime.now()
            
            # Write your data to the current file
            log_entry = f"Log entry at {now.strftime('%Y-%m-%d %H:%M:%S')}\n"
            current_file.write(log_entry)
            current_file.flush()  # Ensure data is written immediately
            
            # Check if 24 hours have passed since last rotation
            time_since_rotation = now - rotation_start
            if time_since_rotation.total_seconds() >= 24 * 3600:
                # Close old file and create new one
                current_file.close()
                current_file = setup_new_file()
                rotation_start = now
                print("Rotated to new log file")
            
            # Wait until the next hour (adjust if you need precise top-of-the-hour writes)
            # Calculate seconds until next hour
            next_hour = now.replace(minute=0, second=0, microsecond=0) + datetime.timedelta(hours=1)
            sleep_seconds = (next_hour - now).total_seconds()
            time.sleep(sleep_seconds)
    except KeyboardInterrupt:
        # Clean up on exit
        current_file.close()
        print("Stopped logging, file closed properly")

if __name__ == "__main__":
    main()

Key Fixes & Explanations

  • Proper File Handling: We explicitly close the old file before opening a new one, and use flush() to ensure data isn't stuck in a buffer during rotation.
  • Precise Time Tracking: Instead of counting loops, we use datetime to calculate the exact time since the last rotation, so we never miss or trigger rotation early.
  • Scheduled Sleep: The script calculates exactly how long to wait until the next hour, avoiding drift that could throw off the 24-hour rotation schedule.
  • Graceful Exit: The try/except block ensures the file is closed properly if you stop the script with Ctrl+C, preventing data loss.

If your original code had specific logic (like custom file naming or specific data to write), you can swap out the log_entry line and setup_new_file function to match your needs.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:35:37