使用python将文本文件转换为csv

时间:2017-10-31 08:55:44

标签: python csv

我有一个这样的文本文件:

Name: John Sanj
Age: 23
Gender: Male

我想在csv中将其转换为:

Name,Age,Gender
John Sanj,23,Male

这是我的代码:

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)

但我得到这样的输出:

Name,Age,Gender

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

2,3

M,a,l,e

1 个答案:

答案 0 :(得分:3)

您将字符串从每行传递到writerow(而不是所有行),并且字符串可以迭代,分成其组成字符。

您应该一次读取所有行,剥离 ': '上的换行符拆分(注意尾随空格) ),然后转置

下面:

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)