我正在从新闻网站抓取数据并将其保存到标题,新闻和img变量中,然后写入csv文件,但是我在每个抓取行中都重复了列名,我只想打印时间列名,然后保存我的抓取数据请帮助我 这是代码
with open(r'C:\Users\Zain Noman\Desktop\DN-data.csv', 'a+', newline='') as file:
writer = csv.writer(file, delimiter=',')
writer.writerow(['title','news','img-url'])
writer.writerows([mylist])
file.close()
答案 0 :(得分:0)
我会这样
file = open('C:\Users\Zain Noman\Desktop\DN-data.csv', 'a+')
writer = csv.writer(file) #csv wrapper
writer.writerow(['title','news','img-url']) #write the header once
writer.writerows(mylist) #write the the entire list assuming its a list of lists
file.close() #close the file connection
答案 1 :(得分:0)
在writerow行使用此答案之前,我已经找到了答案及其简单答案
with open('C:Desktop\DN-data.csv', 'a+', newline='') as file:
writer = csv.writer(file, delimiter=',')
if file.tell() == 0
writer.writerow(['title','news','img-url'])
writer.writerows([mylist])
file.close()