Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert txt to csv python script

Tags:

python

text

csv

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
like image 478
Adam Eliezerov Avatar asked Sep 22 '16 14:09

Adam Eliezerov


3 Answers

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)
like image 169
Tom Yates Avatar answered Oct 21 '22 16:10

Tom Yates


import pandas as pd
df = pd.read_fwf('log.txt')
df.to_csv('log.csv')
like image 20
Kit Stark Avatar answered Oct 21 '22 16:10

Kit Stark


This is how I do it:

 with open(txtfile, 'r') as infile, open(csvfile, 'w') as outfile:
        stripped = (line.strip() for line in infile)
        lines = (line.split(",") for line in stripped if line)
        writer = csv.writer(outfile)
        writer.writerows(lines)

Hope it helps!

like image 3
iun1x Avatar answered Oct 21 '22 16:10

iun1x