Home > front end >  Remove Text from CSV file
Remove Text from CSV file

Time:01-12

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()

CodePudding user response:

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)

CodePudding user response:

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"

  • Related