load a csv file named foo.txt and, depending on the first specified argument to the application, either add a new entry or remove an existing one in python

main.py
import csv
import argparse


def add_entry(file_path, new_entry):
    with open(file_path, mode='a', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(new_entry)


def remove_entry(file_path, entry_to_remove):
    rows_to_keep = []
    with open(file_path, mode='r') as file:
        reader = csv.reader(file)
        for row in reader:
            if row != entry_to_remove:
                rows_to_keep.append(row)
    
    with open(file_path, mode='w', newline='') as file:
        writer = csv.writer(file)
        writer.writerows(rows_to_keep)
        

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Add or remove entry in a CSV file.')
    parser.add_argument('action', type=str, choices=['add', 'remove'], help='Add or remove an entry.')
    parser.add_argument('file_path', type=str, help='Path to the CSV file.')
    parser.add_argument('entry', type=str, nargs='+', help='Entry to add or remove as a list of values separated by commas.')
    args = parser.parse_args()

    if args.action == 'add':
        add_entry(args.file_path, args.entry)
    elif args.action == 'remove':
        remove_entry(args.file_path, args.entry)
1200 chars
35 lines

The above code will accept three positional arguments from the command line:

  • action: the action to perform, either add or remove
  • file_path: the path to the CSV file
  • entry: the entry to add or remove, specified as a list of values separated by commas

It uses the csv module for file handling and data manipulation, and argparse for parsing arguments from the command line.

The add_entry function will append a new entry to the CSV file by opening it in append mode, creating a csv.writer object, and writing the new entry to the file.

The remove_entry function will remove an existing entry from the CSV file by iterating over each row in the file using csv.reader, checking if it is equal to the specified entry to remove, and appending all other rows to a list called rows_to_keep. Then, it will open the file in write mode, create a new csv.writer object, and write only the rows from rows_to_keep back to the file.

The main body of the script first parses the command line arguments using argparse. Depending on the value of args.action, it will either call the add_entry or remove_entry function with the specified file path and entry.

gistlibby LogSnag