使用python将多行txt文件转换为CSV

时间:2019-02-01 13:01:48

标签: python

您好,我正在尝试使用python将某些.txt文件转换为csv文件,但似乎无法对其进行管理。基本上,所有内容都只在一列中,而是分开并在一行中。

.txt文件

   Heading test
Stuff, Stuffing, Stuffer
https://www.test.com/testSearch/test.html

Python

 import csv
import re

with open('string.txt', 'r') as in_file:
    stripped = (line.strip() for line in in_file)
    lines = (re.split(';|,|\n',line) for line in stripped if line)
    with open('log.csv', 'w') as out_file:
        writer = csv.writer(out_file)
        writer.writerow(('title','topic 1', 'topic 2' ,'topic 3','link')) 
        writer.writerows(lines)

输出

title,topic 1,topic 2,topic 3,link

Heading test

Stuff, Stuffing, Stuffer

https://www.test.com/testSearch/test.html

1 个答案:

答案 0 :(得分:0)

尝试以下代码:

import csv

with open('sample.txt', 'r') as in_file:
    stripped = [line.strip() for line in in_file]
    lines = [line.split(",") for line in stripped if line]
    lines1  = [li for line in lines for li in line]
    with open('log.csv', 'wb') as out_file:
        writer = csv.writer(out_file)
        writer.writerow(('title', 'intro'))
        writer.writerow(lines1)