我要分析以下格式的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库,不确定它是否足够我使用,或者我应该编写自己的字符串解析器?你能帮帮我吗?在
最佳
下面的代码可以满足您的需要,并且一次最多只能读取一个部分(为大文件节省内存)。将}分别替换为输入和输出文件路径:
in_path
和{注意,您需要将
line[0] == 'Test'
语句中的'Test'
更改为指示标题行的正确单词。在这里的基本思想是,我们将文件导入到一个列表列表中,然后使用数组理解将该列表写回列表以进行转置(以及在列不均匀时添加空白元素)。在
我将使用一个使用itertools.groupby函数和csv module的解决方案。请仔细看看itertools的documentation你可以比你想象的更频繁地使用它!在
我用空行来区分数据集,这种方法使用惰性求值,一次只在内存中存储一个数据集:
如果提供的数据存储在
^{pr2}$my_data.csv
中,则输出:相关问题 更多 >
编程相关推荐