I have a .txt file with this inside - 2.9,Gardena CA
我有一个内置的.txt文件 - 2.9,Gardena CA.
What I'm trying to do is convert that text into a .csv (table) using a python script:
我想要做的是使用python脚本将该文本转换为.csv(表):
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
我在log.csv文件中得到的输出是 - title,intro,tagline
What I would want the log.csv file to show is:
我希望log.csv文件显示的是:
title,intro
2.9,Gardena CA
2 个解决方案
#1
7
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)
#2
0
I suposse this is the output you need:
我认为这是你需要的输出:
title,intro,tagline
标题,介绍,宣传标语
2.9,Gardena,CA
2.9,加利福尼亚州加迪纳
It can be done with this changes to your code:
可以通过对代码进行此更改来完成:
import csv
import itertools
with open('log.txt', 'r') as in_file:
lines = in_file.read().splitlines()
stripped = [line.replace(","," ").split() for line in lines]
grouped = itertools.izip(*[stripped]*1)
with open('log.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerow(('title', 'intro', 'tagline'))
for group in grouped:
writer.writerows(group)
#1
7
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)
#2
0
I suposse this is the output you need:
我认为这是你需要的输出:
title,intro,tagline
标题,介绍,宣传标语
2.9,Gardena,CA
2.9,加利福尼亚州加迪纳
It can be done with this changes to your code:
可以通过对代码进行此更改来完成:
import csv
import itertools
with open('log.txt', 'r') as in_file:
lines = in_file.read().splitlines()
stripped = [line.replace(","," ").split() for line in lines]
grouped = itertools.izip(*[stripped]*1)
with open('log.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerow(('title', 'intro', 'tagline'))
for group in grouped:
writer.writerows(group)