Python中的CSV解析

2024-09-28 22:33:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我要分析以下格式的csv文件:

Test Environment INFO for 1 line.
Test,TestName1,
TestAttribute1-1,TestAttribute1-2,TestAttribute1-3
TestAttributeValue1-1,TestAttributeValue1-2,TestAttributeValue1-3

Test,TestName2,
TestAttribute2-1,TestAttribute2-2,TestAttribute2-3
TestAttributeValue2-1,TestAttributeValue2-2,TestAttributeValue2-3

Test,TestName3,
TestAttribute3-1,TestAttribute3-2,TestAttribute3-3
TestAttributeValue3-1,TestAttributeValue3-2,TestAttributeValue3-3

Test,TestName4,
TestAttribute4-1,TestAttribute4-2,TestAttribute4-3
TestAttributeValue4-1-1,TestAttributeValue4-1-2,TestAttributeValue4-1-3
TestAttributeValue4-2-1,TestAttributeValue4-2-2,TestAttributeValue4-2-3
TestAttributeValue4-3-1,TestAttributeValue4-3-2,TestAttributeValue4-3-3

并希望将其转换为制表符分隔格式,如下所示:

^{pr2}$

测试属性的数量因测试而异。对于某些测试,只有3个值,而有些测试只有7个值,等等。同样在TestName4示例中,有些测试执行了多次,因此每次执行都有自己的TestAttributeValue行。(在示例中testname4执行了3次,因此我们有3个值行)

我对python不太熟悉,但我想用python解析csv文件。我检查了python的csv库,不确定它是否足够我使用,或者我应该编写自己的字符串解析器?你能帮帮我吗?在

最佳


Tags: 文件csvtest示例格式个值testattribute4testattributevalue3
2条回答

下面的代码可以满足您的需要,并且一次最多只能读取一个部分(为大文件节省内存)。将in_path和{}分别替换为输入和输出文件路径:

import csv
def print_section(section, f_out):
    if len(section) > 0:
        # find maximum column length
        max_len = max([len(col) for col in section])
        # build and print each row
        for i in xrange(max_len):
            f_out.write('\t'.join([col[i] if len(col) > i else '' for col in section]) + '\n')
        f_out.write('\n')

with csv.reader(open(in_path, 'r')) as f_in, open(out_path, 'w') as f_out:
    line = f_in.next()
    section = []
    for line in f_in:
        # test for new "Test" section
        if len(line) == 3 and line[0] == 'Test' and line[2] == '':
            # write previous section data
            print_section(section, f_out)
            # reset section
            section = []
            # write new section header
            f_out.write(line[1] + '\n')
        else:
            # add line to section
            section.append(line)
    # print the last section
    print_section(section, f_out)

注意,您需要将line[0] == 'Test'语句中的'Test'更改为指示标题行的正确单词。在

这里的基本思想是,我们将文件导入到一个列表列表中,然后使用数组理解将该列表写回列表以进行转置(以及在列不均匀时添加空白元素)。在

我将使用一个使用itertools.groupby函数和csv module的解决方案。请仔细看看itertools的documentation你可以比你想象的更频繁地使用它!在

我用空行来区分数据集,这种方法使用惰性求值,一次只在内存中存储一个数据集:

import csv
from itertools import groupby

with open('my_data.csv') as ifile, open('my_out_data.csv', 'wb') as ofile:
    # Use the csv module to handle reading and writing of delimited files.
    reader = csv.reader(ifile)
    writer = csv.writer(ofile, delimiter='\t')
    # Skip info line
    next(reader)
    # Group datasets by the condition if len(row) > 0 or not, then filter
    # out all empty lines
    for group in (v for k, v in groupby(reader, lambda x: bool(len(x))) if k):
        test_data = list(group)
        # Write header
        writer.writerow([test_data[0][1]])
        # Write transposed data
        writer.writerows(zip(*test_data[1:]))
        # Write blank line
        writer.writerow([])

如果提供的数据存储在my_data.csv中,则输出:

^{pr2}$

相关问题 更多 >