<p>请检查以下代码:</p>
<pre><code>import re
import csv
data_list= []
record_data = False
comm_line = False
#Open file read data.
#Save one set of data between 'head' and 'arraydat' in single dict
#Append that dict to data list
with open('sample.txt','r') as new_file:
for line in new_file:
if '( "head"' in line:
record_data = True
data_dict = {}
continue
if '( "arraydat"' in line:
data_list.append(data_dict)
record_data = False
#Data from comm line
if "comm" in line and record_data:
comm_line = True
nline = ''
if comm_line:
n = re.match(r'\s*\)\s*$',line)
if n is not None:
comm_line=False
nline = nline + line.strip('\r\n')
line=re.sub(' +',' ',nline)
n = None
else:
nline = nline + line.strip('\r\n')
next
if record_data:
line = line.strip()
if line.startswith('(') and line.endswith(')'):
line = line.strip(')(').strip()
#line = re.sub('\"',"",line)
#print line
m = re.match(r'\"(\w+)\"\s+\"*([\w+\W+]+)\"*',line)
if m is not None:
k = m.group(1).strip('"')
v = m.group(2).strip('"')
data_dict[k]=v
print data_list
#Write it to csv
with open('output.csv','wb') as out_file:
writer = csv.DictWriter(out_file, fieldnames=data_list[0].keys())
writer.writeheader()
for data in data_list:
writer.writerow(data)
</code></pre>
<p><strong>输出:</strong></p>
<p>控制台上:</em></p>
<pre><code>C:\Users\dinesh_pundkar\Desktop>python b.py
[{'therm': '0', 'probID': '574', 'PartNum': '5418916', 'numrow': '1', 'rev': '1'
, 'ptype': 'probe', 'mux': '1', 'bipolar': 'N/A', 'maker': 'YMS', 'comm': '[ ""
]', 'sn': '11224', 'numel': '192', 'focus': '0.066', 'date': '63602497416.093',
'pname': 'C16D', 'opname': 'Kaji', 'te': '0', 'freq': '3400000'}, {'therm': '0',
'probID': '574', 'PartNum': '5418916', 'numrow': '1', 'rev': '1', 'ptype': 'pro
be', 'mux': '1', 'bipolar': 'N/A', 'maker': 'YMS', 'comm': '[ "" ]', 'sn': '1122
4', 'numel': '192', 'focus': '0.066', 'date': '63602497416.093', 'pname': 'C16D'
, 'opname': 'Dinesh', 'te': '0', 'freq': '3400000'}]
C:\Users\dinesh_pundkar\Desktop>
</code></pre>
<p><em>内容<strong>输出.csv</strong>:</em></p>
<pre><code>therm,probID,PartNum,numrow,rev,ptype,mux,bipolar,maker,comm,sn,numel,focus,date,pname,opname,te,freq
0,574,5418916,1,1,probe,1,N/A,YMS,"[ """" ]",11224,192,0.066,63602497416.093,C16D,Kaji,0,3400000
0,574,5418916,1,1,probe,1,N/A,YMS,"[ """" ]",11224,192,0.066,63602497416.093,C16D,Dinesh,0,3400000
</code></pre>