使用zip函数和writerows创建CSV文件时出现问题

时间:2019-07-15 18:34:19

标签: python-3.x

我是python的新手(学习3周后),正在尝试创建一些代码以从网页中抓取一些数据。我已经能够使用xpath创建一些数据列表。因此,这里有办公室列表和联系人列表。

为了结合它们,我使用了zip功能,如下所示。如果我打印列表(测试),我可以看到我得到了带有一堆元组(例如

)的列表的预期结果
[('\n101 Venture', '\nJeremy Baron'), ('\n1888 Management', '\nTrent May'), ('\n1919 Investment Counsel', "\nHarry O'Mealia"), ('\n2M Companies', '\nAmeeth Sankaran')]

根据以下问题,我正走在正确的道路上:Write a csv file in Python : error with function writerows

但是,只要我打开CSV文件,它就会显示为空。这是我的代码:

# combine lists from scraper
test = zip(office, contact_name)

#make CSV 
with open('some3.csv', 'wt') as csvfile:
    csv_out = csv.writer(csvfile)
    csv_out.writerows(test)

所以不确定我为什么不生成一个以元组为一行并且每个元素以逗号分隔的CSV文件。

1 个答案:

答案 0 :(得分:0)

解决了这个问题

test = zip(office, contact_name)


#make CSV 
with open('some6.csv', 'w+', newline="") as csvfile:
    csv_out = csv.writer(csvfile, delimiter=",")
    for row in test:
        csv_out.writerow(row)