Adam Eliezerov Adam Eliezerov - 2 months ago 13
Python Question

Convert txt to csv python script

I have a .txt file with this inside - 2.9,Gardena CA

What i'm trying to do is convert that text into a .csv (table) using a python script:

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)


The output I get in the log.csv file is - title,intro,tagline

What I would want the log.csv file to show is:

title,intro
2.9,Gardena CA

Answer

You need to split the line first.

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)