简体   繁体   中英

Output py2neo recordlist to text file

I am trying to use python (v3.4) to act as a 'sandwich' between Neo4j and a text output file. This code gives me a py2neo RecordList :

from py2neo import Graph
from py2neo.packages.httpstream import http
http.socket_timeout = 9999
graph = Graph('http://localhost:7474/db/data/')
sCypher = 'MATCH (a) RETURN count(a)'
results = graph.cypher.execute(sCypher)

I also have some really simple text file interaction:

f = open('Output.txt','a') #open for append access
f.write ('\n Hello world')
f.close

What I really want to do is f.write (str(results)) but it really didn't like that at all. Can someone help me to convert my RecordList into a string please? I'm assuming I'll need to loop through the columns to get each column name, then loop through each record and write it individually, but I don't know how to go about this. Where I'm eventually planning to go with this is to change the Cypher every time.

Closest related question I could find is this one: How to convert Neo4j return types to python types . I'm sure there's someone out there who'll read this and say that using the REST API directly is a much better way of spitting out text, but I'm not quite at that level...

Thanks in advance, Andy

Here is how you can iterate a RecordList and print the columns of the individual Records to a file (eg comma separated). If the properties you return are lists you would need some more formatting to get strings for your output file.

# use with to open files, this makes sure that it's properly closed after an exception
with open('output.txt', 'a') as f:
    # iterate over individual Records in RecordList
    for record in results:
        # concatenate all columns of the Record into a string, comma separated
        # list comprehension with str() to handle int and other types
        output_string = ','.join([str(x) for x in record])
        # actually write to file
        print(output_string, file=f)

The format of the output file depends on what you want to do with it of course.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM