简体   繁体   中英

how to write column one time in csv file in python3

i am scraping data from news website and save in to title, news and img variable and then write into csv file but i got the repeatation of column name with each scraping row , i want to print only time column name then save my scraping data plz help me here is the code

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()

see this output pic

I would do it this way

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

I found the answer and its simple before the writerow line use this

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()

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