pythondata-export

save .txt data in excel worksheet


I want to extract data from a .txt file and store it in an excel worksheet. It seems to work but the script does not save all of the data. Here is my code:

def save_excel(filename, date, item, price, counter):
    
    workbook = xlsxwriter.Workbook('Ausgabenliste.xlsx')
    worksheet = workbook.add_worksheet(filename)

    #write header
    worksheet.write(0, 0, "Datum")     
    worksheet.write(0, 1, "Einkauf")     
    worksheet.write(0, 2, "Preis")  

    worksheet.write(counter, 0, date)    
    worksheet.write(counter, 1, item)  
    worksheet.write(counter, 2, price) 

    workbook.close()   

with open (filename) as f:
    lines = f.readlines()
    print(lines)
    counter = 1
    
    for line in lines:
        l=line.split()
        a = l [-3]
        b = l [-2]
        c = l [-1]
        """print(l)
        print(a)
        print(b)
        print(c)
        print(counter)"""
        save_excel(filename,a, b, c, counter)
        counter += 1

The .txt file contains this information:

02.09.2020 Pizza 1,50
02.09.2020 Pizza 1,50
02.09.2020 Nussschnecke 2,05
02.09.2020 jlkjlsdf 546

and the output looks like this:

enter image description here

This is a total noob question. I just don´t understand why the information inbetween is lost.

Thank you very much.


Solution

  • This could be achieved very easily with pandas:

    import pandas as pd
    df = pd.read_csv(filename, sep=" ", columns = ['Datum','Einkauf', 'Preis'])
    df.to_excel('Ausgabenliste.xlsx', sheet_name=filename,index=False)