# Sage Math: How to read input data for a graph from a file

The help center seems to indicate that this topic is suited for here, as software that mathematicians use, apologies if this is incorrect.

So, I'm brand new to Sage, and I've only ever messed with a little Python. (I am an experienced programmer though.)

I'm trying to create a little example in Sage where I construct a graph (graph theory, not coordinate) by reading in a list of nodes and edges from a text file.

I'd like to take input in the following format, where every node name is given, followed by a space, the pipe character, a space, and then a comma spaced list of nodes to create edges to, e.g.:

A | B, C
B | A, J, G, K
C | A
...
J | B, Q


Acceptable methods would be either directly reading and parsing the input from a file stored somewhere, or pasting data from a text file into some kind of text box.

• Personally I think it's more appropriate on stackoverflow or ask.sagemath.org, but luckily you should be in good shape. – kcrisman Feb 8 '17 at 22:56

Basically this should be easy (given your programming background). Three steps.

1. Make all your vertices into strings, "A" instead of A.
2. Turn your list into a Python dictionary, where for each thing before the pipe you associate the list of connected vertices, e.g. {"A":["B","C"]} (except the dict should be all of these correspondences).
3. Turn it into a graph by doing Graph(my_dict).

I think this should work, unless your connection lists are not consistent. See here.

Graph({"A":["B", "C"], "B":["A", "J", "G", "K"],"C":["A"]})


kcrisman has a good answer (which I have accepted because it is correct, even though I prefer mine), but I ended up doing it differently.

First off, I started using a different format. I used a .csv file instead of a .txt file to store the data, and I removed the pipe character entirely; instead, I considered the first token in each row to be the header for that row.

For posterity, my code is here:

graph = Graph()
vertices = list()
edges = list()

def getDataFromFile():
dataFile = open(raw_input('Enter name of csv data file to use:'), 'rt')
try:
for course in row:
if (not course.strip() in vertices):
vertices.append(str(course).strip())
if (not course == row[0]):
edges.append((row[0].strip(), course.strip()))
finally:
dataFile.close()

getDataFromFile()

• If only I could find a Python Library to do my work for me and return a paycheck! – Bassinator Feb 9 '17 at 14:33