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

如何使用split与readlines替换文本文件指定列的数据?

Fixing the Python Code to Update Owner in Hardware.txt

First, let's break down the key issues in your original code, then provide a corrected version that properly uses split() and readlines() to update the specified record.

Key Issues in the Original Code

  • Mixing file iteration and readlines(): When you loop over the file with for data in openingFile:, the file pointer moves forward. Calling readlines() inside this loop reads all remaining lines, breaking the loop's intended logic.
  • Overwriting the entire file: Opening the file in write mode (w) and writing only the modified line deletes all other records entirely.
  • Incorrect split() usage: You split the first line of the file instead of the target record line, so you're trying to replace the header text "Owner" instead of the actual owner name from the selected record.
  • Redundant check: if lines[enterId] in lines: is unnecessary (it's always true if the index is valid) and doesn't handle invalid indices (which would throw an error instead of showing the "no record" message).
  • Lack of error handling: The code doesn't account for non-integer input or record IDs that are out of bounds.

Corrected Code Implementation

Here's a revised version that fixes these issues and follows Python best practices:

try:
    # Get record ID from user (assuming IDs start at 1 for the first data line, skipping header)
    enter_id = int(input("Enter record ID: "))
    
    # Read all lines using a with statement (auto-closes the file safely)
    with open('Hardware.txt', 'r') as file:
        lines = file.readlines()
    
    # Validate the record ID is within valid range
    if 1 <= enter_id < len(lines):
        # Process the target line
        target_line = lines[enter_id].strip()
        line_components = target_line.split()
        
        # Ensure the line has the expected 4 columns
        if len(line_components) == 4:
            new_owner = input("Enter new owner name: ")
            # Replace the 4th component (index 3) with the new owner
            line_components[3] = new_owner
            # Reconstruct the updated line
            updated_line = ' '.join(line_components) + '\n'
            # Update the lines list
            lines[enter_id] = updated_line
            
            # Write all lines back to the file
            with open('Hardware.txt', 'w') as file:
                file.writelines(lines)
            
            print(f"Record {enter_id} updated successfully: {updated_line.strip()}")
        else:
            print("Error: The target line doesn't match the expected format.")
    else:
        print(f"There is no record with ID {enter_id}. Valid IDs are 1 to {len(lines)-1}.")
except ValueError:
    print("Error: Please enter a valid integer for the record ID.")

Explanation of the Corrected Code

  • with statements: These automatically close files after operations, preventing resource leaks and ensuring clean file handling.
  • Reading all lines at once: readlines() loads all lines into a list, making it easy to modify specific entries and write everything back without losing data.
  • ID validation: We check if the entered ID falls within the range of valid data lines (skipping the header at index 0).
  • Targeted splitting: We split only the line we want to modify, not the first line of the file, so we're working with the correct owner value.
  • Reconstructing the line: After updating the owner, we join the components back into a string and update our lines list.
  • Writing all lines: Using writelines() writes every line (including the modified one) back to the file, preserving all other records.
  • Error handling: The try-except block catches non-integer input, and we handle invalid ID ranges and malformed lines gracefully.

Example Usage

If you enter 1 as the record ID and John as the new owner, your Hardware.txt file will update to:

Model Year Plate Owner
Acer (2014) A12456 John
Dell (2015) S45656 Dane

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:42:31