mujahir
mujahir

Reputation: 187

Coverting a text file into csv using python

I have a text file like this:

Name: John Sanj
Age: 23
Gender: Male

I want to covert it in csv like this:

Name,Age,Gender
John Sanj,23,Male

Here is my code:

import csv
import os
filepath=os.path.normpath('C:\\Users\\Desktop\\new\\ac.txt')
with open(filepath, 'r') as f:
    with open('log.csv', 'w') as out_file:
        writer = csv.writer(out_file)
        writer.writerow(('Name', 'Age','Gender'))
        for line in f:
            x=line.split(':')
            x[-1]=x[-1].strip()
            b=x[1]
            writer.writerow(b)

But I am getting output like this:

Name,Age,Gender

J,o,h,n, ,S,a,n,j

2,3

M,a,l,e

Upvotes: 1

Views: 75

Answers (1)

Moses Koledoye
Moses Koledoye

Reputation: 78546

You're passing the strings from each line to writerow (instead of all the lines), and strings being iterable, get splitted into their constituent characters.

You should read all the lines at once, strip the newline character, split on ': ' (notice the trailing space), and then transpose.

Here:

with open(filepath) as f, open('log.csv', 'w') as out_file:
    writer = csv.writer(out_file)
    rows = zip(*[line.rstrip().split(': ') for line in f])
    writer.writerows(rows)

Upvotes: 3

Related Questions