Home > Software engineering >  write the data into particular column CSV python tkinter
write the data into particular column CSV python tkinter

Time:10-05

I am writing the data into the csv file. I want to append the data row by row. How do I achieve that?

    # opening the csv file in 'w ' mode
    file = open(filename, 'w ', newline ='')
      
    # writing the data into the file
    with file:         
        writer.writerow(['Column1', 'Column2', 'Column3'])
        for items in self.data_List:                
            print('items', items)
            writer.writerow([items, self.displayData112, self.displayData])

How to append the next data in next row for particular column .

CodePudding user response:

method 1:

First make a header for your CSV:

with file:
    # identifying header  
    header = ['Column1', 'Column2', 'Column3']
    writer = csv.DictWriter(file, fieldnames = header)
      
    # writing data row-wise into the csv file
    writer.writeheader()

Then add the data you want, under those headers ,using dictionary; like this:

    # this part is also in the `with` block.
    for items in self.data_List:                
        print('items', items)
        writer.writerow({'Column1' : items, 'Column2': self.displayData112, 'Column3': self.displayData})

method 2:

Use pandas in order to append the data frame to an existing file, row wise:
As you said in the comments, that;

the self.displayData112 has only one row data

Just append the self.displayData112 once, afterwards append "" (empty string) to the Column2:

import pandas as pd

# make the data you have, as a dictionary
data = {'Column1':[], 'Column2':[], 'Column3':[]}
is_displayData112_added = False
for items in self.data_List:
    data["Column1"].append(items)
    if is_displayData112_added:
        data["Column2"].append("")
    else:
        data["Column2"].append(self.displayData112)
        is_displayData112_added = True
    data["Column3"].append(self.displayData)

# dataframe from dictionary
df = pd.DataFrame(data)

# append this `df` to the existing `csv` file:  
df.to_csv(filename, mode='a', index=False, header=False)
  • Related