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

CSV文件指定文本移除需求及现有Python脚本问题排查

Fixing Your CSV Text Removal Script: Stop Unwanted Output Files & Add "NOPE" Handling

Let's tackle the two core issues with your script right away:

  1. It creates an Output.csv even when no matching text is found (just copying the original content)
  2. It doesn't print "NOPE" when there's nothing to remove (the try/except block only catches errors, not missing matches)

Here's a revised, cleaner version that fixes both problems and adds safer file handling:

import csv

target_text = input("Enter the text you want to remove from the CSV: ")
has_modifications = False
modified_rows = []

# First, read and process all rows to check for changes
with open('Input.csv', 'r') as input_file:
    reader = csv.reader(input_file)
    for row in reader:
        modified_row = []
        for value in row:
            if target_text in value:
                has_modifications = True
                modified_row.append(value.replace(target_text, ''))
            else:
                modified_row.append(value)
        modified_rows.append(modified_row)

# Only create the output file if we actually made changes
if has_modifications:
    with open('Output.csv', 'w', newline='') as output_file:
        writer = csv.writer(output_file)
        writer.writerows(modified_rows)
    print("Modified CSV saved as Output.csv")
else:
    print("NOPE")

Key Changes Explained:

  • Track modifications explicitly: We added a has_modifications flag to detect if any value in the CSV contained the target text. This lets us decide whether to generate the output file or not.
  • Safer file management: Using with statements ensures files are automatically closed, even if something goes wrong (no more leftover open file handles).
  • Avoid unnecessary file creation: We only open the output file after confirming changes were made—no more empty or unmodified Output.csv files cluttering things up.
  • Ditch the misused try/except: Your original try/except was catching errors (like missing input files) instead of checking for matches. This version focuses on intentional logic for your use case.

Why Your Original Script Failed:

  • You opened the output file immediately, so it was created before you even checked if any text needed removing.
  • The try/except block didn't serve your intended purpose—it only handled errors, not the scenario where no matches were found. So even with no changes, it wrote all original rows to the output file.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 18:10:31