Search code examples
pythonpandasdataframeexport-to-csvexport-to-excel

How can I export for loop result to CAV or Excel with pandas?


I have a for loop gets datas from a website and would like to export it to xlsx or csv file. Normally when I print result of loop I can get all list but when I export that to xlsx file only get last item. Where is the problem can you help?

for item1 in spec:
        spec2 = item1.find_all('th')
        expl2 = item1.find_all('td')
        spec2x = spec2[a].text
        expl2x = expl2[a].text
        yazim = spec2x + ': ' + expl2x
        cumle = yazim
        patern = r"(Brand|Series|Model|Operating System|CPU|Screen|MemoryStorage|Graphics Card|Video Memory|Dimensions|Screen Size|Touchscreen|Display Type|Resolution|GPU|Video Memory|Graphic Type|SSD|Bluetooth|USB)"
        if re.search(patern, cumle):
            speclist = translator.translate(cumle, lang_tgt='tr')
            specl = speclist                         
            #print(specl) 
            import pandas as pd
            exp = [{ 'Prospec': specl,},] 
            df = pd.DataFrame(exp, columns = ['Prospec',])
            df.to_excel('output1.xlsx',)

Solution

  • Create an empty list and, at each iteration in your for loop, append a data frame to the list. You will end up with a list of data frames. After the loop, use pd.concat() to create a new data frame by concatenating every element of your list. You can then save the resulting df to an excel file.

    Your code would look something like this:

    import pandas as pd
    df_list = []
    
    for item1 in spec:
        ......
        if re.search(patern, cumle):
            .... 
            df_list.append(pd.DataFrame(.....))
    
    df = pd.concat(df_list)
    df.to_excel(.....)