Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

How can we convert a .txt file into a CSV python script file?

Here, I'm trying to convert it:

import csv

import itertools

with open('log.txt', 'r') as in_file:

    stripped = (line.strip() for line in in_file)

    lines = (line for line in stripped if line)

    grouped = itertools.izip(*[lines] * 3)

    with open('log.csv', 'w') as out_file:

        writer = csv.writer(out_file)

        writer.writerow(('title', 'intro'))

        writer.writerows(grouped)

But, In the output, I can get only the title, intro, and tagline

I need the log.csv file to show:

title,intro

2.9,Gardena CA

1 Answer

0 votes
by (26.4k points)

Here, First you need to split the line

import csv

with open('log.txt', 'r') as in_file:

    stripped = (line.strip() for line in in_file)

    lines = (line.split(",") for line in stripped if line)

    with open('log.csv', 'w') as out_file:

        writer = csv.writer(out_file)

        writer.writerow(('title', 'intro'))

        writer.writerows(lines).

Want to know more about python? Come and join: python certifcation course

Related questions

0 votes
1 answer
0 votes
2 answers
asked Sep 17, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

Browse Categories

...