Need help writing my write to csv code

Hello, I’m trying to create a work database for myself. I’m fairly new to this and am piecing it together as I go. I’ve created an HTML form as the origin of the info. On save, the information is sent to a csv file for storage. At the moment, the header is sent every time. I’m having trouble writing this so that the header only prints the 1st time, then subsequently only the values are sent. There’s a lot of information out there, but I can’t pinpoint exactly what I need here.

Also if there are areas to simplify, let me know.

@app.route("/", methods=["POST", "GET"])
def customer_info():
    if request.method == "POST":
        first_name = request.form['firstname']
        last_name = request.form['lastname']
        company = request.form['company']
        email_address = request.form['email']
        phone_number = request.form['phonenumber']
        address = request.form['address']
        address_2 = request.form['address2']
        city = request.form['city']
        state = request.form['state']
        zip_code = request.form['zipcode']
        with open("customer_info.csv", mode="a", newline="") as csvfile:
            fieldnames = ["First Name", "Last Name", "Company", "Email Address", "Phone Number", "Address", "Address 2", "City", "State", "ZIP Code"]
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerow({
                "First Name": first_name,
                'Last Name': last_name,
                'Company': company,
                'Email Address': email_address,
                'Phone Number': phone_number,
                'Address': address,
                'Address 2': address_2,
                'City': city,
                'State': state,
                'ZIP Code': zip_code,
            })
    return render_template("customer_info.html")

Welcome to the group, Michael…

You need to skip the call to writer.writeheader() except on the first run. If you don’t know if the file already exists, call os.path.exists("customer_info.csv") before the with statement. If it doesn’t exist, write a header, otherwise skip that…

1 Like

Hello,

I actually have a similar script where I write records to an Excel file - on a row by row basis.

You can do this by reading the rows where the headers are located on your csv file. If the row cells where the headers are, are emply, then you should write/print the headers. Otherwise, if not empty, ignore. Via pseudo code, it works something like this:

read Header cells 

If empty:
   write headers:

This guarantees that they are only written if the values that you read are emply.

1 Like

Thanks Skip! It makes total sense.

Thanks Paul! Yes, that does seem like what I’m looking for. I’ll give it a shot.

Well, I don’t know if this is the most efficient way, but I got it to work. Thank you Skip and Paul for your direction.

@app.route("/", methods=["POST", "GET"])
def customer_info():
    if request.method == "POST":
        first_name = request.form['firstname']
        last_name = request.form['lastname']
        company = request.form['company']
        email_address = request.form['email']
        phone_number = request.form['phonenumber']
        address = request.form['address']
        address_2 = request.form['address2']
        city = request.form['city']
        state = request.form['state']
        zip_code = request.form['zipcode']

        if not os.path.exists("customer_info.csv") or os.stat("customer_info.csv").st_size == 0:
            with open("customer_info.csv", mode="w") as csvfile:
                fieldnames = ["First Name", "Last Name", "Company", "Email Address", "Phone Number", "Address", "Address 2", "City", "State", "ZIP Code"]
                writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
                writer.writeheader()
                writer.writerow({
                    "First Name": first_name,
                    'Last Name': last_name,
                    'Company': company,
                    'Email Address': email_address,
                    'Phone Number': phone_number,
                    'Address': address,
                    'Address 2': address_2,
                    'City': city,
                    'State': state,
                    'ZIP Code': zip_code,
                })
        else:
            with open("customer_info.csv", mode="a", newline="") as csvfile:
                fieldnames = ["First Name", "Last Name", "Company", "Email Address", "Phone Number", "Address", "Address 2", "City", "State", "ZIP Code"]
                writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
                writer.writerow({
                    "First Name": first_name,
                    'Last Name': last_name,
                    'Company': company,
                    'Email Address': email_address,
                    'Phone Number': phone_number,
                    'Address': address,
                    'Address 2': address_2,
                    'City': city,
                    'State': state,
                    'ZIP Code': zip_code,
                })
    return render_template("customer_info.html")
2 Likes