I am writing a Python script to write data to a CSV file. The data is passed by parameter, for which I use the argparse library. It is also important that the data has a certain order so that it matches the CSV header. Another feature of the script is that the user does not know all the data at once, but learns it over a period of time. This means that the user can specify the data for the CSV in any order and the script then orders them so that they have the correct order in the CSV as mentioned.
An example: There are parameters a and b.
Within the CSV, the data of parameter a must come before that of parameter b
However, the user executes the script with parameter b first because he does not yet know the data of parameter a.
In addition, the data should be retained in the CSV, even if not all parameters are specified.
My problem is as follows
1. I can't manage to write the parameter data in the correct order in the CSV script.
2. In addition, the script overwrites the data of the previous execution in the CSV if I no longer specify the previous parameter (it thinks that if I no longer specify the parameter that it has the value “n/a" and overwrites the data in the field with “n/a").
Also to mention: I'm not very experienced in Python, so I hope this problem won't hold you up too long.
Here is an example of my script. It should work like this and show what I described above.
from argparse import ArgumentParser
from pathlib import Path
import csv
# creating parser and the arguments
# nargs='?' means that the parameter is optional
parser = ArgumentParser()
# data before drive
# ---
parser.add_argument('--file', type=Path)
parser.add_argument('--data1', type=str, nargs="?", default="n/a")
parser.add_argument('--data2', type=str, nargs="?", default="n/a")
parser.add_argument('--date', type=str, nargs="?", default="n/a")
# parse arguments into "args" var
args = parser.parse_args()
# specify rows and fields of the csv file
fields = ['Driver', 'Data 1', 'Data 2', 'Date']
rows = {'Drive Number': args.driveNr, 'Data 1': args.data1, 'Data 2': args.data2, 'Date': args.date}
# open the csvfile and write the parameters value inside
with open(args.file, 'r+') as csvfile:
writer = csv.DictWriter(csvfile, rows.keys())
writer.writeheader()
writer.writerow(rows)