![](/img/trans.png)
[英]How can I extract information from a recordList returned as node in python using py2neo?
[英]Output py2neo recordlist to text file
我正在嘗試使用python(v3.4)作為Neo4j和文本輸出文件之間的“三明治”。 這段代碼給了我一個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)
我也有一些非常簡單的文本文件交互:
f = open('Output.txt','a') #open for append access
f.write ('\n Hello world')
f.close
我真正想做的是f.write (str(results))
但它根本不喜歡。 有人可以幫我將RecordList轉換為字符串嗎? 我假設我需要遍歷各列以獲取每個列名,然后遍歷每條記錄並分別寫入,但是我不知道該如何做。 我最終打算采用的方法是每次都更改Cypher。
我可以找到的最接近的相關問題是這個: 如何將Neo4j返回類型轉換為python類型 。 我確定那里有人會讀這本書,並說直接使用REST API是吐出文本的更好的方法,但是我還不算這個水平...
在此先感謝,安迪
這是您可以迭代RecordList
並將單個Records
的列打印到文件中的方法(例如,逗號分隔)。 如果返回的屬性是列表,則需要更多格式來獲取輸出文件的字符串。
# 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)
當然,輸出文件的格式取決於您要使用的格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.