user4850448
user4850448

Reputation:

Export processed text in a csv file in Python

I have the following piece of code:

csv_file = 'similarweb/domains.csv'
file_in = open(csv_file, 'r')
file_out = open(csv_file, 'w')

with file_in as csv_read_file:
    reader = csv.reader(csv_read_file)
    for i, line in enumerate(reader):
        url = ', '.join(str(e) for e in line)
        final_result = url + " " + (content_client.category(url)['Category'])
        print final_result

file_in.csv:

word1
word2
...
word_n

file_out.csv - this is how print final_result looks like.

word1 explanation1
word2 explanation2
word_n explanation_n

This successfully takes as an input some rows from a csv file and add some information to each row. How can I export final_result in file_out ?

Upvotes: 1

Views: 70

Answers (1)

maxymoo
maxymoo

Reputation: 36545

How about this:

csv_file = 'similarweb/domains.csv'

final_result = ""
with open(csv_file, 'r') as csv_read_file:
    reader = csv.reader(csv_read_file)
    for i, line in enumerate(reader):
        url = ', '.join(str(e) for e in line)
        final_result += url + " " + (content_client.category(url)['Category']) + "\n"

with open(csv_file, 'w') as csv_write_file:
    csv_write_file.write(final_result)

Upvotes: 1

Related Questions