main.py1200 chars35 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 fileentry
: the entry to add or remove, specified as a list of values separated by commasIt 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