[Tutor] mapping list appends to correct position for csv output

Norman Khine norman at khine.net
Tue Nov 13 10:50:35 CET 2012


hello,
i am trying to create a csv file in python and map the fields to a
pre-existing fields, here is the title fileds of my csv


c = csv.writer(open("adm_products.csv", "wb"), delimiter='\t',
quotechar='"', quoting=csv.QUOTE_ALL)

import_fields = ["ID", "Active (0/1)", "Name *", "Categories (x,y,z...)",
                "Price tax excl. or Price tax incl.", "Tax rules ID",
"Wholesale price", "On sale (0/1)",
                "Discount amount", "Discount percent", "Discount from
(yyyy-mm-dd)", "Discount to (yyyy-mm-dd)",
                "Reference #", "Supplier reference #", "Supplier",
"Manufacturer", "EAN13", "UPC", "Ecotax", "Weight",
                "Quantity", "Short description", "Description", "Tags
(x,y,z...)", "Meta-title", "Meta-keywords",
                "Meta-description", "URL rewritten", "Text when in
stock", "Text when backorder allowed",
                "Available for order (0 = No, 1 = Yes)", "Product
creation date", "Show price (0 = No, 1 = Yes)",
                "Image URLs (x,y,z...)", "Delete existing images (0 =
No, 1 = Yes)", "Feature(Name:Value:Position)",
                "Available online only (0 = No, 1 = Yes)",
"Condition", "ID / Name of shop"]

so for example:

adm_product = []
for category in breadcrumbs.findAll('li', { "class" :
re.compile(r'\bcategory\d')}):
    adm_product.append(category.find('a').renderContents()) # MAP TO CATEGORY

product_shop = soup.find('div', attrs={"class": "product-shop"})
product_sku = soup.find('p', attrs={"class": "product-sku"})
if product_sku:
    sku = product_sku.renderContents()
    product_ref = ref(sku)[0]
    adm_product.append(product_ref) # MAP TO REFERENCE #

short_description = soup.find('div', attrs={"class": "short-description"})
if short_description:
    short_desc = short_description.find('div', attrs={"class": "std"})
    if short_desc:
        adm_product.append(short_desc.renderContents()) # MAP TO SHORT
DESCRIPTION


What is the correct way to map the product_ref to the Reference # in
the import_fields list with any missing values being left blank or
create a csv so that when i append a value it is added to the correct
column?

also which is more efficient:

c.writerow(adm_product) # writing the product to the csv when all the
fileds are found

or

products = [] # adding them to a list first and then writing them to the csv
products.append(adm_product)
c.writerow(x) for x in products


More information about the Tutor mailing list