New to python. I'm reading from file line by line:
with open("graph.txt", "r") as f:
comList = f.readlines()
print(comList)
edge_u = [x[0] for x in comList]
edge_v = [x[1] for x in comList]
graph.txt has :
[(0, 7), (1, 9), (1, 9), (2, 0)]
[(2, 1), (2, 1), (3, 6)]
I was expecting that readlines will parse the file line by line hence will parse the text as a list of list. But its parsing it as List of strings. Hence i;m unable to perform the other two operations. Tried to print edge_u and get to know what its parsing. How to deal with this? Thanks.
4 Answers 4
You may try this:
import ast
with open("test.txt", "r") as f:
for line in f:
li = ast.literal_eval(line)
edge_u = [x[0] for x in li]
edge_v = [x[1] for x in li]
5 Comments
with.for line in f.readlines() is redundant. for line if f is all you need.f can be interated directly, yes.ast.literal_eval instead of direct eval being used in other answers. It's safer.file.readlines([size]) returns size bytes worth of lines or all lines as a list of strings. I believe what you want if you want to parse this file would be json.
from json import loads
with open('graph.txt', 'r') as fob:
comList = [loads(line) for line in fob]
edge_u = [x[0] for x in comList]
edge_v = [x[1] for x in comList]
You could use eval but be careful not to catch something exceptional:
In [1]: tmp = eval("[(0, 7), (1, 9), (1, 9), (2, 0)]")
In [2]: tmp
Out[2]: [(0, 7), (1, 9), (1, 9), (2, 0)]
Otherwise, you have to manually parse the string (what is actually the better solution).
Comments
As suggested already, you can use eval
with open("graph.txt","r") as f:
lines = f.readlines()
comList = list(map(eval, lines))
print(type(comList), comList)
edge_u = [x[0] for x in comList]
edge_v = [x[1] for x in comList]
print(type(edge_u), edge_u)
print(type(edge_v), edge_v)
which produces
<class 'list'> [[(0, 7), (1, 9), (1, 9), (2, 0)], [(0, 7), (1, 9), (1, 9), (2, 0)]]
<class 'list'> [(0, 7), (0, 7)]
<class 'list'> [(1, 9), (1, 9)]