[英]Convert txt to csv python script
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 文件中得到的输出是 - 标题、介绍、标语
What I would want the log.csv file to show is:我希望 log.csv 文件显示的是:
title,intro
2.9,Gardena CA
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)
import pandas as pd
df = pd.read_fwf('log.txt')
df.to_csv('log.csv')
I suposse this is the output you need:我认为这是您需要的输出:
title,intro,tagline
标题、介绍、标语
2.9,Gardena,CA
2.9,加德纳,CA
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)
This is how I do it:这就是我的做法:
with open(txtfile, 'r') as infile, open(csvfile, 'w') as outfile:
stripped = (line.strip() for line in infile)
lines = (line.split(",") for line in stripped if line)
writer = csv.writer(outfile)
writer.writerows(lines)
Hope it helps!希望有帮助!
In python version 3.x, the intertools.izip is not operate.在python 3.x 版本中,intertools.izip 没有运行。
The functional code for Python 3 is: Python 3 的功能代码是:
import csv
import zlib
with open('output.txt', 'r') as in_file:
lines = in_file.read().splitlines()
stripped = [line.replace(","," ").split() for line in lines]
grouped = zip(*[stripped]*1)
with open('teste.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerow(('A', 'B', 'C', 'D'))
for group in grouped:
writer.writerows(group)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.