用Python将gml文件中边的信息输出为csv(或者txt)格式

时间:2023-01-05 21:02:49

最近在做复杂网络方面的内容,初学python。需要将gml格式的图的信息中边的信息提取出来,输出为csv格式和txt格式。

英文描述如下: Use python to convert the edge information stored in gml file to a new cvs file.

代码如下:

def gml2csv(gmlfile):
"""
This function is used to convert a gml file into csv format.
The graph information included in the gml file will be stored in the csv
file as edges with the format 'vertex1 vertex2\n'
gmlfile: The name of the gml file. Path and postfix should be included.
"""
(filepath, shotname) = get_file_name(gmlfile)
g = igraph.Graph.Read_GML(gmlfile)
newfile = open(filepath + shotname + '.csv', 'wb')
writer = csv.writer(newfile, dialect = 'excel')
for line in g.get_edgelist():
writer.writerow(line)
return


注意csv.writer的使用。如果是一次性写入一个sequence,用writerows(some_sequence),如果只有一项,用writerow