简体   繁体   中英

Python CSV append new row

So here is my issue, I have created a Dictionary for my lists and am trying to add the data I find and append it to each row but instead it is just appending to the same column with the same data type.

How could I get it so each new append add to new row.

data_dict = {'contact name': [], 'name': [], 'telephone': [], 'email': [],
        'mobile': [], 'feedback average': []}

try: 
        data_dict['telephone'].append(soup.find('span',itemprop='telephone').text)
    except AttributeError: 
        data_dict['telephone'].append('No telephone')

 print data_dict
field_names = fn = data_dict.keys()
with open('./file.csv','w') as csvfile:
    f = csv.DictWriter(csvfile, fieldnames=fn)

    f.writeheader()
    f.writerow(data_dict)

Try something like this:

data_dict = {'contact name': [], 'name': [], 'telephone': [], 'email': [],
    'mobile': [], 'feedback average': []}

try:
    data_dict['telephone'].append(soup.find('span',itemprop='telephone').text)
except AttributeError: 
    data_dict['telephone'].append('No telephone')

print data_dict
fn = data_dict.keys()
with open('./file.csv','w') as csvfile:
    f = csv.reader(csvfile)
    for row in f:
        for i in len(fn):
            data_dict[fn[i]].append(row[i])

This should work for you, if I got you right. But care, this requires that one row in the csv contains exactly the elements of your dictionary, in the correct order.

If this isn't the case, you will need to find out which value is written in which column, and then add the value of this column to the list in your dictionary.

So you would need to replace

for i in len(fn):
    data_dict[fn[i]].append(row[i])

by

for k in fn:
    data_dict[k].append(row[columns[k]])

where columns is a dictionary that contains the same keys as data_dict, and as the values the columns in which the data of the specific key is stored in the csv-file. For an example, columns could look like this:

columns = {'contact name': 1, 'name': 3, 'telephone' : 6, 'email': 7, 'mobile':8, 'feedback average': 2}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM