0

I am stuck with a problem and I would like to get input from you guys.

I am coding a Neo4J application using py2neo. I want to read a file and use that file to create the nodes and relationships

The problem I have is that the file input using code below, gives the lines back as a string.

file = "../create_db"
dbFile=open(file,'r')

And what I need is, instead of getting it back as a string, to get it raw.
At the moment the problem is that I want:

graph_db.create(node({'Id':'1', 'Description':'Computer'}))

But I get:

graph_db.create("node({'Id':'1', 'Description':'Computer'})")

Is there a way to get file input raw? Maybe an library that gives it back raw?

Thanks in advance, Jiar

fredtantini
  • 15,966
  • 8
  • 49
  • 55
Jiar
  • 3
  • 2
  • You mean the file contains code statements (or partially statements)? Perhaps take a look at the `eval` function... – isedev Oct 01 '14 at 14:47
  • Thank you very much, it worked. Add an answer so i can gibe u some credits for it. – Jiar Oct 01 '14 at 14:49

2 Answers2

0

It seem your input file contains code statements (or partial code statements).

You can execute the statements using the eval builtin function and pass the results of that to the graph_db.create function.

However, you should be aware this allows arbitrary code to be executed (i.e. the input file becomes part of the executing script) and should be treated as part of the code (i.e. don't use an untrusted input file).

isedev
  • 18,848
  • 3
  • 60
  • 59
0

You could also check the ast module. Although I don't know if this will work in your case (emphasis mine):

ast.literal_eval(node_or_string)

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.

So maybe if you have some control on the file to only use the dict part…

Using eval can be dangerous. Check also this question and its answers.

Community
  • 1
  • 1
fredtantini
  • 15,966
  • 8
  • 49
  • 55