[英]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. 我正在尝试使用python(v3.4)作为Neo4j和文本输出文件之间的“三明治”。 This code gives me a py2neo RecordList : 这段代码给了我一个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. 我真正想做的是f.write (str(results))
但它根本不喜欢。 Can someone help me to convert my RecordList into a string please? 有人可以帮我将RecordList转换为字符串吗? 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. 我最终打算采用的方法是每次都更改Cypher。
Closest related question I could find is this one: How to convert Neo4j return types to python types . 我可以找到的最接近的相关问题是这个: 如何将Neo4j返回类型转换为python类型 。 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... 我确定那里有人会读这本书,并说直接使用REST API是吐出文本的更好的方法,但是我还不算这个水平...
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). 这是您可以迭代RecordList
并将单个Records
的列打印到文件中的方法(例如,逗号分隔)。 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. 当然,输出文件的格式取决于您要使用的格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.