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

如何用Python修改txt指定行字符串:将true替换为false

Fixing the Projection Deletion Script

Let's walk through what's wrong with your current code and fix it step by step:

Issues in Your Original Code

  • You modify the matching line's field in a temporary list, but don't save all lines (modified and unmodified) anywhere. When you write to the file, you just dump the string "false" which wipes out your entire file content.
  • You don't need to manually call close() when using with statements—they automatically handle file cleanup once the block finishes.
  • You don't persist any of your changes to memory before overwriting the file, so your modifications are lost immediately after the loop.

Corrected Code

def delete_projection():
    # Store all processed lines here to preserve data
    updated_projections = []
    delete_code = input("Input projection code you want to delete: ")
    
    # Read the original file and process each line
    with open('projections.txt', 'r') as projections_file:
        for line in projections_file:
            # Remove trailing newline and split fields by |
            projection_fields = line.strip().split('|')
            # Check if this is the projection we need to mark as deleted
            if projection_fields[0] == delete_code:
                projection_fields[8] = 'false'
            # Reconstruct the line in the original format and add to our list
            updated_line = '|'.join(projection_fields) + '\n'
            updated_projections.append(updated_line)
    
    # Write all processed lines back to the file (overwrites original)
    with open('projections.txt', 'w') as projections_file:
        projections_file.writelines(updated_projections)

# Run the function
delete_projection()

What This Fixes

  1. Preserves All Data: We collect every line (modified or not) in the updated_projections list, so no existing projections get lost.
  2. Maintains File Format: Using '|'.join() ensures we keep the original pipe-separated structure after modifying the field.
  3. Safe File Handling: The with statements take care of opening/closing files properly, avoiding resource leaks.
  4. Clearer Logic: We separate reading/processing from writing, making the code easier to follow and debug.

How to Test

If you input 0002 when prompted, the second line in projections.txt will change from:

0002|BB|19.12.2017.|19:30|21:15|sreda|March on the Drina|300|true

to:

0002|BB|19.12.2017.|19:30|21:15|sreda|March on the Drina|300|false

All other lines will remain exactly as they were.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:34:47