Python按自然周每分钟写入CSV,每周新建文件的实现求助
Solution for Weekly Rotating CSV Logs (Minute-by-Minute Writes)
Hey there! Let's break down how to build this system step by step—since you're new to Python, I'll keep things straightforward and explain each part clearly.
Core Concepts to Cover
We need three main pieces to make this work:
- Time tracking: Detect when a new natural week starts to switch CSV files
- Scheduled writes: Trigger a write operation every minute
- File management: Safely close the old file and create a new one when the week changes
Step 1: Choose the Right Tools (All Standard Library!)
We'll use Python's built-in modules so you don't need to install anything extra:
datetime: To handle dates, weeks, and timestamps for your datacsv: To properly write structured data to CSV files (avoids formatting issues)time: To handle delays between writessignal: (Optional) To handle clean shutdowns if you interrupt the script
Step 2: Define "Natural Week"
First, let's lock down what a natural week means. We'll use ISO 8601 weeks (Monday as the first day, Sunday as the last)—this is the most common standard globally. If you need a different start day (like Sunday), we can adjust that later.
To get the current week identifier (unique even across years), we'll use:
current_week = f"{datetime.date.today().isocalendar()[0]}_{datetime.date.today().isocalendar()[1]}" # Example output: "2024_23" for the 23rd week of 2024
Step 3: Full Working Code Example
Here's a complete script with explanations:
import csv import datetime import time import signal # Global variables to track the current file and week current_file = None csv_writer = None active_week = "" def close_file(): """Safely close the current CSV file if it's open""" global current_file if current_file: current_file.close() current_file = None print("Closed previous week's CSV file") def open_new_week_file(): """Create a new CSV file for the current week and initialize the writer""" global current_file, csv_writer, active_week # Generate a unique filename based on year and week today = datetime.date.today() active_week = f"{today.isocalendar()[0]}_w{today.isocalendar()[1]}" filename = f"data_{active_week}.csv" # Open the file in write mode (starts fresh each week) current_file = open(filename, "w", newline="", encoding="utf-8") csv_writer = csv.writer(current_file) # Write header if it's a new file csv_writer.writerow(["timestamp", "example_data"]) print(f"Opened new CSV file: {filename}") def write_data(): """Write a single row of data to the CSV""" global active_week, csv_writer # Get current time for the timestamp now = datetime.datetime.now().isoformat() # Replace this with your actual data data_point = "sample_value" # Check if we're still in the same week today = datetime.date.today() current_week = f"{today.isocalendar()[0]}_w{today.isocalendar()[1]}" if current_week != active_week: close_file() open_new_week_file() # Write the data row csv_writer.writerow([now, data_point]) # Force write to disk immediately (prevents data loss if the script crashes) current_file.flush() print(f"Wrote data at {now}") def handle_shutdown(signum, frame): """Clean up files when the script is interrupted (Ctrl+C)""" print("\nShutting down...") close_file() exit(0) # Register the shutdown handler for Ctrl+C signal.signal(signal.SIGINT, handle_shutdown) # Initialize the first file open_new_week_file() # Main loop: write every minute while True: write_data() # Wait 60 seconds before next write (adjust to 10s for testing!) time.sleep(60)
Key Explanations
- File Management: The
close_file()andopen_new_week_file()functions handle switching files cleanly. We use a unique filename with year and week to avoid overwriting old data. - Data Writing: We flush the file after each write to make sure data isn't stuck in memory (critical if the script unexpectedly stops).
- Clean Shutdown: The
handle_shutdown()function ensures the file is closed properly if you press Ctrl+C, preventing corrupted CSV files. - Testing Tip: For testing, change
time.sleep(60)totime.sleep(10)(10 seconds) and manually adjust your system date to the next week to verify the file switch works.
Troubleshooting Common Issues
- Permission Errors: Make sure your script has write access to the directory where it's running.
- CSV Formatting: Using the
csvmodule instead of writing raw strings ensures commas/newlines in your data don't break the file structure. - Time Drift: If you need super precise timing (not just "roughly every minute"), you can replace
time.sleep(60)with code that calculates the next full minute to wait for—let me know if you need that!
内容的提问来源于stack exchange,提问作者Green
相关产品推荐
相关产品推荐

