-2

I am trying to remove a particular text from a CSV file. If it matches, I want it to remove the string and create a new csv file with the same data, but without the text.

If it doesn't I want it to not create a new CSV file and also print "NOPE".

My current script removes the text from the original CSV file if it matches, and creates a new CSV file. If the text I enter is incorrect, it creates a new CSV file, but doesn't change anything or print out my error message.

Here is my current code:

import csv

result = input("Enter the text you want to remove from the CSV: ")

input_file = open('Input.csv', 'r')
output_file = open('Output.csv', 'w', newline='')
data = csv.reader(input_file)
writer = csv.writer(output_file)

def DEL():
    try:
        for line in data:
            line = [value.replace(result, '') for value in line]
            writer.writerow(line)
    except Exception:
        print('NOPE')
DEL()
fjm
  • 3
  • 2
  • What exception are you expecting in the try/except block? `.replace()` does not raise an exception if the text to be replaced is not found in the string, if that's what you were thinking... – John Gordon Jan 12 '23 at 03:45
  • "If the text I enter is incorrect, it creates a new CSV file, but doesn't change anything or print out my error message." Well, why do you suppose that happens? (Hint: where the code says `output_file = open('Output.csv', 'w', newline='')`, what do you think this means? Does that happen before `DEL` runs, or after? Therefore, does it care about what happens inside `DEL`)? – Karl Knechtel Jan 12 '23 at 03:58
  • Aside from that: in your own words, what do you think `try` and `except Exception:` mean? How do you intend for the logic to work? What kind of exception do you expect will be raised if the string is not present in the file, and why? – Karl Knechtel Jan 12 '23 at 03:59
  • Aside from that: if you process the file one line at a time, and write each line as it's processed - what happen when the file doesn't contain the input? **How can you know whether that is the case, until** you have read the entire file? (After all, it could still be in the part that hasn't been read yet - right?) So, think more carefully about the intended steps, and the order they need to happen. – Karl Knechtel Jan 12 '23 at 04:01

2 Answers2

0

I think you are misinterpreting how a try statement works. In a "try" statement the "except" statement is only executed if the code inside the "try" statement crashes, ie raises an error. If it executes without error the "except" statement does not execute. To make this work, you must test for the existence of the string first and if it does not, print "NOPE", else execute change - INSIDE the "try" section:

import csv


def fn_del():
    str_found = False
    try:
        for lines in data:
            for each_line in lines:
                if result in each_line:
                    line = [value.replace(result, '') for value in each_line]
                    writer.writerow(line)
                    print("string found")
                    str_found = True
    except Exception:
        print('Code crashed')
    finally:
        if not str_found:
            print("NOPE")


result = input("Enter the text you want to remove from the CSV: ")
input_file = open('/home/desktopbackup/Documents/Input.csv', 'r')
output_file = open('Output.csv', 'w', newline='')
data = csv.reader(input_file)
writer = csv.writer(output_file)

fn_del()

Also re-arranged code a bit to make it more "pythonic"

Galo do Leste
  • 703
  • 5
  • 13
0

Your code never tests for result in any of the CSV cells, so you don't have a way to decide whether to write a new file or not. You could scan the CSV once and break on the first match. This can be done with the any() function and generators that check the cell values of each row. After that, you can use writerows and a similar set of generators to write the new file.

import csv

def DEL(in_csv_name, out_csv_name, result):
    with open(in_csv_name, newline="") as in_file:
        needs_change = any(any(result in cell for cell in row)
            for row in csv.reader(in_file))
    if needs_change:
        with (open(in_csv_name, newline="") as in_file,
                open(out_csv_name, "w", newline="") as out_file):
            csv.writer(out_file).writerows(
                [cell.replace(result, '') for cell in row]
                for row in csv.reader(in_file))
    else:
        print("NOPE")

result = input("Enter the text you want to remove from the CSV: ")
                    
DEL("Input.csv", "Output.csv", result)
tdelaney
  • 73,364
  • 6
  • 83
  • 116