如何将此文本文件格式解析为CSV格式? [英] How to parse this text file format into CSV format?

查看:90
本文介绍了如何将此文本文件格式解析为CSV格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样布置的文本文件,其中每个字段都是换行符:

I have a text file laid out as such where every field is a new line:

id = 606149
Category Name = Structural Columns
Family Name = Concrete-Square-Column
Type Name = EXIST RH C1 16 x 16
Document = 15050 Peavy Struct v2016_detached
Attachment Justification At Top = Minimum Intersection
Image = <None>
Offset From Attachment At Top = 0
id = 606151
Category Name = Structural Columns
Family Name = Concrete-Square-Column
Type Name = EXIST RH C2 16 x 16
Document = 15050 Peavy Struct v2016_detached
Attachment Justification At Top = Minimum Intersection
Image = <None>
Offset From Attachment At Top = 0

在我的代码中,我打开文本文件进行读取,并打印出前三行进行测试.当我尝试在行末添加逗号时,我在下面的行中得到逗号:

In my code I open the text file for reading and print out the first three lines for testing. When I try to append a comma to the end of the line I get the comma in the line below:

def main():
   count = 0
   filename = "test.txt"
   file = open(filename, "r")
   for line in file:
      if count == 3:
         break
      count = count + 1
      line += ','
      print line

使用此代码,我得到结果:

With this code I get the result:

id = 606149
,
Category Name = Structural Columns
,
Family Name = Concrete-Square-Column
,

在连接逗号之前添加线条以剥离新行时:

When I add a line strip to strip new lines before I concatenate the comma:

line = line.strip('\n')"

我得到这个结果:

,id = 606149
,ategory Name = Structural Columns
,amily Name = Concrete-Square-Column

我无法将此文件解析为CSV格式.

I'm having trouble parsing this file into a CSV format.

推荐答案

这应该有效

line.rstrip("\n") + ","

这篇关于如何将此文本文件格式解析为CSV格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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