Home > Software engineering >  How to print values for two columns of a .csv file using python
How to print values for two columns of a .csv file using python

Time:05-03

I am generating below data inside a for loop

2021-08-01 ['I', 'go', 'home']
2021-08-01 ['They', 'are', 'doing', 'great']
2021-08-02 ['We', 'are', 'here']
2021-08-02 ['You', 'are', 'awesome']

What I want to do is that I want to print above content to a .csv file of two columns Date & Text (Sample as below)

Date            Text
2021-08-01      ['I', 'go', 'home']
2021-08-01      ['They', 'are', 'doing', 'great']
2021-08-02      ['We', 'are', 'here']
2021-08-02      ['You', 'are', 'awesome']

    for key, val in res.items():
    keywords = []
    scores = []
    for index in val:
        keywords.append(index)
        scores.append(val[index])
    for i in find_clusters(keywords, scores):
        repA = list(dict.fromkeys(w for s in i for w in s.split()))
        print(key, repA)#this is where I print above values

CodePudding user response:

To get file like

2021-08-01 ['I', 'go', 'home']
2021-08-01 ['They', 'are', 'doing', 'great']
2021-08-02 ['We', 'are', 'here']
2021-08-02 ['You', 'are', 'awesome']

you can even open file at start and use it with print()

fh = open("output.txt", "w")

# ... code ...

print(key, repA, file=fh)

# ... code ...

fh.close()

But this file will make problem to read it.

It would be better to use modulecsv to write it

import csv

fh = open("output.csv", "w")
writer = csv.writer(fh)

writer.writerow(["Date", "Text"])

# ... code ...

writer.writerow( [key, repA] )

# ... code ...

fh.close()

Or you can put all in list and use pandas to write csv or excel (or write to some database)

import pandas as pd


all_rows = []

# ... code ...

all_rows.append( [key, repA] )

# ... code ...

df = pd.DataFrame(all_rows, columns=["Date", "Text"])

df.to_csv("output.csv", index=False)

# or

df.to_excel("output.xlsx", index=False)
  • Related