Python文件指定文本追加方法及考勤CSV程序选项2报错排查
Hey there! Let's break down your questions and fix that code issue step by step.
1. How to Append Content After Specific Text in a File with Python
Modifying files by inserting content after a specific string isn't as straightforward as appending to the end—since files are stored as sequential data, you can't just "insert" in the middle directly. Here are two reliable approaches:
Method 1: Read, Modify, Rewrite (Best for Small Files)
Read the entire file into memory, find the target text, append your new content right after it, then write everything back to the file:
def append_after_target(file_path, target_text, new_content): # Read all lines from the file with open(file_path, 'r') as f: lines = f.readlines() # Rewrite the file with modified content with open(file_path, 'w') as f: for line in lines: f.write(line) # Append new content immediately after the target line if target_text in line: f.write(f"{new_content}\n")
Method 2: Use a Temporary File (Best for Large Files)
For big files that you don't want to load entirely into memory, use a temporary file to process lines one by one, then replace the original file:
import tempfile import shutil def append_after_target_large(file_path, target_text, new_content): # Create a temporary file to store modified content with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file: with open(file_path, 'r') as original_file: for line in original_file: temp_file.write(line) if target_text in line: temp_file.write(f"{new_content}\n") # Replace the original file with the temporary one shutil.move(temp_file.name, file_path)
2. Fixing Your Attendance System Code
Let's look at why option 2 was failing, then fix it:
What Was Wrong?
- File pointer issues with
r+mode: When you open a file inr+and read all lines, the file pointer moves to the end—so any writes after that get appended to the end of the file, not modifying the target line. - Stale
attend1value:attend1was computed once when the program started, not when the user actually recorded their in time. If the user waited to select option 2, this value wouldn't match the actual in time entry. - Unmanaged file handles: You opened the file multiple times without proper closure, which can lead to unexpected behavior.
Corrected Code
from datetime import datetime def get_formatted_datetime(): # Helper function to get consistent datetime strings return datetime.now().strftime("%d/%m/%Y , %H:%M:%S") name = input("Enter name of employee: ") filename = "Attend.csv" while True: print("\n1. Enter In Time\n2. Enter Out Time") choice = input("Enter your choice: ") if choice == "1": in_time = get_formatted_datetime() entry = f"{name} , {in_time}" print(f"Recorded in time: {entry}") # Use 'with' to auto-close the file after writing with open(filename, "a") as f: f.write(f"{entry}\n") elif choice == "2": out_time = get_formatted_datetime() out_time_only = out_time.rpartition(' , ')[2] # We're looking for the employee's in-time entry (no out time yet) target_prefix = f"{name} , " # Read all existing entries with open(filename, 'r') as f: lines = f.readlines() entry_updated = False # Rewrite the file with updated content with open(filename, 'w') as f: for line in lines: stripped_line = line.strip() # Check if this is an in-time entry (only 2 parts: name + in time) if stripped_line.startswith(target_prefix) and len(stripped_line.split(' , ')) == 2: updated_line = f"{stripped_line} , {out_time_only}\n" f.write(updated_line) entry_updated = True print(f"Updated attendance: {updated_line.strip()}") else: f.write(line) if not entry_updated: print(f"Error: No in-time entry found for {name}. Please record in time first.") else: print("Please choose a valid option (1 or 2).") break
Key Fixes & Improvements:
withstatements for file handling: Automatically closes files, preventing handle leaks and conflicts.- Dynamic target matching: Instead of relying on a stale
attend1value, we check for entries that start with the employee's name and don't have an out time yet. - Proper file rewrite: For option 2, we read all lines, modify the relevant entry, then rewrite the entire file—this avoids the file pointer issues from
r+mode. - User feedback: Tells the user if no in-time entry exists, so they know to record that first.
内容的提问来源于stack exchange,提问作者mahi chauhan
相关产品推荐
相关产品推荐

