我有一个大的csv文件,我正在检查每一行的第二列,然后在另一个csv文件中写入此行。我使用Python 3.5
我的csv文件如下所示:
node_1,type,node_2
154555,intermediary,154587
1545877,president,145888
4575885,intermediary,4785774
我需要为每种类型提供不同的csv文件(中间人,总统......)
import csv
import os.path
i = 0
list = []
with open('all_edges.csv', 'r') as edges:
edges_reader = csv.reader(edges)
for row in edges_reader:
if row[1] not in list:
list.append(row[1])
while row[1] != list[i]:
i += 1
if i != 0:
if not os.path.exists(r'./edges%d.csv' %i):
with open('edges%d.csv' %i, "w+", newline='') as new_edges:
edges_writer = csv.writer(new_edges)
edges_writer.writerow(["node_1", "rel_type", "node_2"])
with open('edges%d.csv' %i, "a+", newline='') as new_edges:
edges_writer = csv.writer(new_edges)
edges_writer.writerow(row)
i = 0
您对如何避免在每一行打开和关闭输出文件有任何建议。
由于