简体   繁体   English

Python CSV追加新行

[英]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. 所以这是我的问题,我为列表创建了一个Dictionary,并尝试添加找到的数据并将其追加到每一行,但只是将其追加到具有相同数据类型的同一列。

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. 但是请注意,这要求csv中的一行以正确的顺序准确包含字典中的元素。

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. 其中column是一个字典,包含与data_dict相同的键,而作为值的列是将特定键的数据存储在csv文件中的列。 For an example, columns could look like this: 例如,列可能如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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