GiveItAwayNow
GiveItAwayNow

Reputation: 447

Separate one column to several in csv

I have a layout for data:

experiences: [{
        company: String,
        title: String,
        description: String,
        startDate: Date,
        endDate: Date   
    }],

and I need to write data in csv in this format, but I don't is it possible to do this. It must be like in excel.

enter image description here

If i choose header expirience I need to get all headers(company, title, description, startDate, endDate) and all data. Also I need to have an opportunity to choose subheader and its data.

Is it possible to do in csv?

Upvotes: 0

Views: 108

Answers (2)

peak
peak

Reputation: 116690

There are various definitions of (and standards) for "CSV" so it's not entirely clear what you are asking, but if you want to embed multi-column data within a single column of a CSV file, then that can usually be done by selecting a suitable distinct field-separator character for the embedded data.

For example, assuming commas are used for the "top-level" separator, it is often convenient to use the "pipe" ("|") character as the next-level separator. In your case, it seems unlikely that the embedded attributes (company, title, description, and dates) will themselves contain the pipe character, so the pipe would probably be a sensible choice, though it would be wise to include software for ensuring the values are "sanitized" in some way.

In general, some care is needed when selecting the pair of separator characters. If comma/pipe does not work, then maybe tab/pipe will.

Upvotes: 0

inspectorG4dget
inspectorG4dget

Reputation: 113915

If you want to write your data to a csv file:

import csv
import operator

data = operator.itemgetter('company', 'title', 'description', 'startDate', 'endDate')

with open('path/to/output', 'w') as fout:
    outfile = csv.writer(fout)
    for e in experiences:
        outfile.writerow([str(d) for d in data(e)])

If you want to read specific column data from a csv file:

import csv
import operator

data = operator.itemgetter(0,3,4)  # or whichever columns you want
experiences = []
keys = 'company startDate endDate'.split()  # the column headers of those columns
with open('path/to/csv') as infile:
    for _ in range(2): infile.readline()
    for row in csv.reader(infile):
        experiences.append(dict(zip(keys, data(row))))

Upvotes: 1

Related Questions