Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why export only last value in list when using writerow function

I have a list of 19 businesses retrieved from scraping website as follow:

for firm in firms: 
    name = firm.find('h3', class_='company-name').text
    mst = firm.find('p', class_=False).get_text(strip=True).split('-')[0].split(':')[1]
    print(name,mst)

CÔNG TY CỔ PHẦN ĐẦU TƯ THƯƠNG MẠI LUCKY HOÀNG MINH  0110306061 
CÔNG TY CỔ PHẦN SUFAM VIỆT NAM  0110306304 
CÔNG TY TNHH TMDV THT VIỆT NAM  0110306449 
CÔNG TY CỔ PHẦN  THƯƠNG MẠI KIẾN TRÚC NỘI THẤT THIÊN ANH LUXURY  0110305942 
CÔNG TY TNHH TMDV BLUESEA TRAVEL  0110305614 
CÔNG TY TNHH KINH DOANH THƯƠNG MẠI LTD  0110306495 
CÔNG TY TNHH DỊCH VỤ THƯƠNG MẠI IN VIỆT HÀ  0110305621 
CÔNG TY TNHH  CÔNG NGHỆ KỶ NGUYÊN CODE  0110306375 
CÔNG TY CỔ PHẦN THỜI TRANG THIẾT KẾ CELAS  0110306424 
CÔNG TY CỔ PHẦN ĐẦU TƯ HD SOLUTIONS  0110306431 
CÔNG TY CỔ PHẦN CƠ KHÍ ĐẠI NAM VINA  0110306294 
CÔNG TY TNHH NỘI THẤT GEN Z  0110306103 
CÔNG TY CỔ PHẦN TƯ VẤN ĐẦU TƯ VÀ XÂY DỰNG HACONS  0110306311 
CÔNG TY TNHH MINKY MOM BABY  0110306079 
CÔNG TY TNHH THƯƠNG MẠI PHONG VY  0110305981 
CÔNG TY TNHH THƯƠNG MẠI VÀ CÔNG NGHỆ QUANG MINH VIỆT NAM  0110306350 
CÔNG TY TRÁCH NHIỆM HỮU HẠN PHÚ HƯNG TÂM  0110306336 
CÔNG TY TNHH CƠ ĐIỆN NAM PHÁT  0110305999 
CÔNG TY TNHH THƯƠNG MẠI AN VƯỢNG PHÁT  0110305974

But when I try to use write row to export data to excel, the only value I got is about the last value (CÔNG TY TNHH THƯƠNG MẠI AN VƯỢNG PHÁT 0110305974):

with open('names.csv', 'w', newline='', encoding="utf-8") as file:
    header = ['Name', 'Tax code']
    writer = csv.DictWriter(file, delimiter=',',lineterminator='\n', fieldnames=header)
    writer.writeheader()
    
    for firm in firms: 
        name = firm.find('h3', class_='company-name').text
        
        mst = firm.find('p', class_=False).get_text(strip=True).split('-')[0].split(':')[1]
    
    print(name,mst)
    writer.writerow({header[0]:name, header[1]: mst})

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your writer.writerow() needs to be inside the for loop

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading