Home > front end >  read all fields of a csv file in python
read all fields of a csv file in python

Time:02-01

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?

CodePudding user response:

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")
  • Related