csv
使用模块的一种简单方法-
import csv
with open('<inputfile>','r') as f , open('<outputfile>','w') as of:
reader = csv.reader(f, delimiter=' ')
writer = csv.writer(of, delimiter=' ')
for lines in reader:
key = lines.pop(0)
for i in range(0,len(lines),2):
writer.writerow([key, lines[i], lines[i+1]])
示例/演示 -
我的a.csv
——
A B 0.4 C 0.3
B C 0.1 E 0.4
C D 0.2 E 0.3
代码 -
>>> import csv
>>> with open('a.csv','r') as f , open('b.csv','w') as of:
... reader = csv.reader(f, delimiter=' ')
... writer = csv.writer(of, delimiter=' ')
... for lines in reader:
... key = lines.pop(0)
... for i in range(0,len(lines),2):
... writer.writerow([key, lines[i], lines[i+1]])
输出b.csv
-
A B 0.4
A C 0.3
B C 0.1
B E 0.4
C D 0.2
C E 0.3