read all fields of a csv file in python

Question:

I have a problem reading a csv file. Each line of the csv file is separated by ,
My edge.csv file looks like this:

source,target,genre
apple,banana,28
strawberry,mango,30
so on.....

So this is my code for read edge.csv file:

def read_net(filename):
    g = nx.Graph()
    with open(filename,encoding="ISO-8859-1",newline="") as f:
        f.readline()
        for l in f:
            l = l.split(",")
            g.add_edge(l[0], l[1], l[2])    //my error is here
    return g
read_net("edge.csv")

My code don’t work because my code can’t read "genre" field of edge.csv file.
It’s like my code only reads the first two fields and not the third one as well. Why?
This is my error:

TypeError: Graph.add_edge() takes 3 positional arguments but 4 were given

how can i read all three fields of the edge.csv file?

Asked By: Elly

||

Answers:

From the documentation:

Graph.add_edge(u_of_edge, v_of_edge, **attr)

Add an edge between u and v.

The nodes u and v will be automatically added if they are not already in the graph.

Edge attributes can be specified with keywords or by directly accessing the edge’s attribute dictionary.

So you should build a graph using source and target with genre that is not clear at all what it should be? Is it the weight of the connection? A numeric feature associated with the connection?

def read_net(filename):
    g = nx.Graph()
    with open(filename,encoding="ISO-8859-1",newline="") as f:
        f.readline()
        for l in f:
            source, destination, genre = l.split(",")
            g.add_edge(source, destination)
    return g
read_net("edge.csv")

For now this will get you started, when you find out more info on the genre field you can think about how to incorporate it into the graph.


In case genre is the weight of the connection:

def read_net(filename):
    g = nx.Graph()
    with open(filename,encoding="ISO-8859-1",newline="") as f:
        f.readline()
        for l in f:
            source, destination, genre = l.split(",")
            g.add_edge(source, destination, weight=genre)
    return g
read_net("edge.csv")
Answered By: Caridorc
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.