在python和csv模块中解析和保存csv文件 [英] parsing and saving csv file in python and csv module

查看:218
本文介绍了在python和csv模块中解析和保存csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此脚本旨在从csv文件解析和排序列表,并保存到新创建的csv文件(包括标题)。

This script is meant to parse and sort a list from a csv file and save to a newly created csv file, including headers.

我triyng包括写入功能,以保存此解析器的输出到一个新的csv文件与以下。

I triyng to include the write function to save the output of this parser to a new csv file with the following. This code create a csv but record the headers only and in one column.

这里是输入:

Timestamp,Session Index,Event,Description,Version,Platform,Device,User ID,Params,
"Dec 27, 2014 05:26 AM",1,NoRegister,,1.4.0,iPhone,Apple iPhone 5c (GSM),,{},
"Dec 27, 2014 05:24 AM",1,NoRegister,,1.4.0,iPhone,Apple iPhone 5c (GSM),,{},
"Dec 27, 2014 05:23 AM",1,HomeTab,Which tab the user viewed ,1.4.0,iPhone,Apple iPhone 5s (GSM),,{ UserID : 54807;  tabName : Home},
"Dec 27, 2014 05:23 AM",2,HomeTab,Which tab the user viewed ,1.4.0,iPhone,Apple iPhone 5s (GSM),,{ UserID : 54807;  tabName : Home},
"Dec 27, 2014 05:23 AM",3,HomeTab,Which tab the user viewed ,1.4.0,iPhone,Apple iPhone 5s (GSM),,{ UserID : 54807;  tabName : QuickAndEasy},

这里是我想要保存到csv的输出:

Here's the output I'd like to get saved to csv:

Timestamp,Session Index,Event,Description,Version,Platform,Device,User ID,TabName,RecipeID,Type,SearchWord,IsFromLabel,
"Dec 27, 2014 05:26 AM",1,NoRegister,,1.4.0,iPhone,Apple iPhone 5c (GSM),,,,,,,
"Dec 27, 2014 05:24 AM",1,NoRegister,,1.4.0,iPhone,Apple iPhone 5c (GSM),,,,,,,
"Dec 27, 2014 05:23 AM",1,HomeTab,Which tab the user viewed ,1.4.0,iPhone,Apple iPhone 5s (GSM),54807,Home,,,,,
"Dec 27, 2014 05:23 AM",2,HomeTab,Which tab the user viewed ,1.4.0,iPhone,Apple iPhone 5s (GSM),54807,Home,,,,,
"Dec 27, 2014 05:23 AM",3,HomeTab,Which tab the user viewed ,1.4.0,iPhone,Apple iPhone 5s (GSM),54807,QuickAndEasy,,,,,

代码:

import csv


def printfields(keys, linesets):
    output_line = ""
    for key in keys:
        if key in linesets:
            output_line += linesets[key] + ","
        else:
            output_line += ","
    print output_line


def csvwriter(reader, path):
    """
    write reader to a csv file path
    """
    with open(path, "w") as csv_file:
        writer = csv.writer(csv_file, delimiter=",")
        for line1 in line:
            if line1 in path:
                writer.writerow(line1)

if __name__ == "__main__":
    fields = [
        "UserID", "tabName", "RecipeID", "type", "searchWord", "isFromLabel", "targetUID"
    ]
    mappedLines = {}
    with open('test.csv', 'r') as f:
        reader = csv.DictReader(f)
        for line in reader:
            fieldPairs = [
                p for p in
                line['Params'].strip().strip('}').strip('{').strip().split(';')
                if p
            ]
            lineDict = {
                pair.split()[0].strip(): pair.split(':')[1].strip()
                for pair in fieldPairs
            }
            mappedLines[reader.line_num] = lineDict
        path = "output.csv"
        csvwriter(reader, path)

    for key in sorted(mappedLines.keys()):
        linesets = mappedLines[key]
        printfields(fields, linesets)


推荐答案

在您的代码中有几个问题

You have several problems in your code,

首先将此文件移到文件顶部

First take this to top of your file

fields = [
    "Timestamp","Session Index","Event","Description","Version","Platform","Device","User ID","Params",""
]

使用 DictWriter 写入 dict

def csv_writer(lines, path):
    """
    write reader to a csv file path
    """
    with open(path, "w") as csv_file:
        writer = csv.DictWriter(csv_file, fields)
        writer.writeheader()
        # Iterate over dict
        for line1, val in lines.iteritems():
            writer.writerow(val)

使用映射

        csv_writer(mappedLines, path)

这篇关于在python和csv模块中解析和保存csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆