[英]How to parse this text file format into CSV format?
我有這樣一個文本文件,其中每個字段都是新行:
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格式。
您可以讀取整個文件和分割行
filename = "text.txt"
file = open(filename, "r")
f = file.read().splitlines()
for line in f:
print(line)
您可以這樣做以獲得所需的輸出,但是您必須提及:
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,
附件對齊方式,頂部=最小交集,圖像=頂部偏移量= 0,
如果數據文件的結構如上所示,則可以使用'='分隔每個鍵值對,將它們存儲到每行的字典中,然后在完全讀取每條記錄后(即找到“偏移量...”鍵值)開始另一行。
擁有所有數據后,請使用csv模塊寫入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
這應該工作
line.rstrip("\n") + ","
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.