我有一个文本文件,每个字段都是一个新行:
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
在我的代码中,我打开文本文件进行阅读,并打印出前三行进行测试。当我尝试将逗号附加到行尾时,我在下面的行中输入逗号:
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
使用此代码我得到结果:
id = 606149
,
Category Name = Structural Columns
,
Family Name = Concrete-Square-Column
,
在连接逗号之前添加换行符以删除新行:
line = line.strip('\n')"
我得到了这个结果:
,id = 606149
,ategory Name = Structural Columns
,amily Name = Concrete-Square-Column
我无法将此文件解析为CSV格式。
答案 0 :(得分:0)
您可以阅读整个文件和分割线
filename = "text.txt"
file = open(filename, "r")
f = file.read().splitlines()
for line in f:
print(line)
答案 1 :(得分:0)
你可以这样做以获得所需的o / p,但是你必须提到这一点:
with open('j.txt', 'r') as f:
d =f.readlines()
for i in d:
i = i.rstrip('\n')
i+=','
print(i)
我在这里使用了rstrip
它会打印所有的行,前三行你可以给出一些循环或条件。
O / P是这样的:
id = 606149, 类别名称=结构列, 姓氏= 混凝土方柱, 类型名称= EXIST RH C1 16 x 16, 文件= 15050 Peavy Struct v2016_detached,
附件理由,顶部= 最小交叉点, Image =从顶部的附件偏移= 0,
答案 2 :(得分:0)
如果您的数据文件的结构如上所示,您可以使用'='分隔每个键值对,然后在完全读取每个记录后将这些存储到每行的字典中(即找到'偏移量'。 ..'键值)开始另一行。
获得所有数据后,请使用csv module编写csv文件。
import csv
data = []
with open('test.txt') as fin:
row = {}
for line in fin:
key, val = line.strip().split(' = ')
row[key] = val
if key == 'Offset From Attachment At Top':
data.append(row)
row = {}
fieldnames = data[0].keys()
with open('test.csv') as fout:
cw = csv.DictWriter(fout, fieldnames)
cw.writerows(data)
您可能希望添加一些错误检查,并且可能希望限制对DictWriter
的调用中字段名称的顺序。我建议你将每一行设为OrderedDict
答案 3 :(得分:0)
这应该有效
line.rstrip("\n") + ","