0

I have a regularly appended CSV file with two types of similar data. I can't control how the data come into the CSV - but I want to execute a python script that will format the CSV so that I can ingest it into a database. Here is what I want to do:

Incoming raw data look like this:

record, date & time, sensor, height, status

record, date & time, sensor, height, weight, status

The idea would be to just take these data iteratively add a comma after height if no weight or something like that. Essentially mimic a blank field so that the data would essentially look like this:

record, date & time, sensor, height, **weight,**status (updated after python script if/then)

record, date & time, sensor, height, weight, status

Hopefully that makes sense - Basically adding a field and I would run the script every time the file is updated.

1
  • Do You care about csv escaping and quotes? Commented Oct 22, 2013 at 14:33

1 Answer 1

2
import csv
import os
with open('yourfile.csv') as f_in, open('yourfile.csv.temp') as f_out:
    reader = csv.reader(f_in)
    writer = csv.writer(f_out)
    for row in reader:
        if len(row) == 5:
            row.insert(4, '')
        writer.writerow(row)
os.rename('yourfile.csv.temp', 'yourfile.csv')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.