我在csv中有数据:
Minneapolis-St. Paul-Bloomington MN-WI--33460 Charlotte-Gastonia-Rock Hill NC-SC--16740 Las Vegas-Paradise NV--29820 New York-White Plains-Wayne NY-NJ (MSAD)--35620
我们如何在列之前仅打印数据?
i.e only : Minneapolis-St. Paul-Bloomington MN-WI Charlotte-Gastonia-Rock Hill NC-SC Las Vegas-Paradise NV & so on....
代码:
#!/usr/bin/python
import csv
import re
sample="""columnA,ColumnB,columnC
1,Cleveland-Elyria-Mentor OH--17460
2,Dallas-Plano-Irving TX (MSAD)--19100
3,ASJDFJKDJ-kD-JE WA--21092"""
open('sample.csv','w').write(sample)
with open('sample.csv') as sample, open('final_output.csv','w') as output:
reader = csv.reader(sample)
writer = csv.writer(output)
# discard input header
next(reader)
# write output header
writer.writerow(['col1','col2','col3'])
#process rows
for row in reader:
if row:
for fipsplit in row[1].split('\n'):
fipsval = re.findall(r'--(\d+)$', fipsplit)
writer.writerow([fipsplit])
print open('final_output.csv').read()
答案 0 :(得分:0)
>>> line = " Minneapolis-St. Paul-Bloomington MN-WI--33460"
>>> line.split("--")[0]
' Minneapolis-St. Paul-Bloomington MN-WI'
使用--
作为字段分隔符,并在分割行