如何用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 usingwithstatements—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
- Preserves All Data: We collect every line (modified or not) in the
updated_projectionslist, so no existing projections get lost. - Maintains File Format: Using
'|'.join()ensures we keep the original pipe-separated structure after modifying the field. - Safe File Handling: The
withstatements take care of opening/closing files properly, avoiding resource leaks. - 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
相关产品推荐
相关产品推荐

