Randal
Randal

Reputation: 431

python csv file add to field based off another field

I have a csv file looks like this:

CSV File

I have a column called “Inventory”, within that column I pulled data from another source and it put it in a dictionary format as you see.

What I need to do is iterate through the 1000+ lines, if it sees the keywords: comforter, sheets and pillow exist than write “bedding” to the “Location” column for that row, else write “home-fashions” if the if statement is not true.

I have been able to just get it to the if statement to tell me if it goes into bedding or “home-fashions” I just do not know how I tell it to write the corresponding results to the “Location” field for that line.

In my script, im printing just to see my results but in the end I just want to write to the same CSV file.

from csv import DictReader
with open('test.csv', 'r') as read_obj:
    csv_dict_reader = DictReader(read_obj)
    for line in csv_dict_reader:
        if 'comforter' in line['Inventory'] and 'sheets' in line['Inventory'] and 'pillow' in line['Inventory']:
            print('Bedding')
            print(line['Inventory'])
        else:
            print('home-fashions')
            print(line['Inventory'])

Upvotes: 0

Views: 106

Answers (2)

Pramote Kuacharoen
Pramote Kuacharoen

Reputation: 1541

The last column of your csv contains commas. You cannot read it using DictReader.

import re

data = []
with open('test.csv', 'r') as f:
    # Get the header row
    header = next(f).strip().split(',')
    for line in f:
        # Parse 4 columns
        row = re.findall('([^,]*),([^,]*),([^,]*),(.*)', line)[0]
        # Create a dictionary of one row
        item = {header[0]: row[0], header[1]: row[1], header[2]: row[2],
                header[3]: row[3]}
        # Add each row to the list
        data.append(item)

After preparing your data, you can check with your conditions.

for item in data:
    if all([x in item['Inventory'] for x in ['comforter',  'sheets', 'pillow']]):
        item['Location'] = 'Bedding'
    else:
        item['Location'] = 'home-fashions'

Write output to a file.

import csv
with open('output.csv', 'w') as f:
    dict_writer = csv.DictWriter(f, data[0].keys())
    dict_writer.writeheader()
    dict_writer.writerows(data)

Upvotes: 1

SamR
SamR

Reputation: 336

csv.DictReader returns a dict, so just assign the new value to the column:

if 'comforter' in line['Inventory'] and ...:
    line['Location'] = 'Bedding'
else:
    line['Location'] = 'home-fashions'
print(line['Inventory'])

Upvotes: 0

Related Questions