1

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

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks,but I wiil be reading a lot of text files and convert them into a single csv file.I want to display the key(Name,Age,Gender) only once.
Then you can write the header (i.e. first line) once, and always discard the header from the other files since the header is the same.
How to discard the header?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.