将 txt 转换为 csv python 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39642082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:31:35  来源:igfitidea点击:

Convert txt to csv python script

pythoncsvtext

提问by Adam Eliezerov

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

回答by Tom Yates

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)

回答by Kit Stark

import pandas as pd
df = pd.read_fwf('log.txt')
df.to_csv('log.csv')

回答by iun1x

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!

希望能帮助到你!

回答by rodmartinez

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)