Home > Blockchain >  Save list without square brackets to a file
Save list without square brackets to a file

Time:07-15

I am trying to save a list as a file in python. Please see my list:

result_list = [[{'head': 'Netgear','type': 'product or material produced',
'tail': 'smarten up an old TV'}], 
[{'head': 'Dirty and Coating Defects',
'type': 'subclass of',
'tail': 'Coating Defects'}]]

However, I aim to save my list in the following format (without the square brackets splitting the lists/strings):

for i in result_list:
    print(*i, end =", ")

which returns the following:

{'head': 'Netgear', 'type': 'product or material produced', 'tail': 'smarten up an old TV'}, {'head': 'Dirty and Coating Defects', 'type': 'subclass of', 'tail': 'Coating Defects'},

Is there any manner to do this effectively, so when I read the file it opens it immediately as the above format? It would be great if it does not take into account the last comma, as this should be deleted.

Thank you in advance.

New piece of code to read the data back in:

    from neo4j import GraphDatabase
import pandas as pd

# Define Neo4j connection
host = 'bolt://3.87.6.145:7687'
user = 'neo4j'
password = 'signalman-leaps-silk'
driver = GraphDatabase.driver(host,auth=(user, password))

def run_query(query, params={}):
    with driver.session() as session:
        result = session.run(query, params)
        return pd.DataFrame([r.values() for r in result], columns=result.keys())



#[{'head': 'Works', 'type': 'different from', 'tail': 
'wonderfully'}, {'head': 'wonderfully', 'type': 'different from', 
'tail': 'Works'}]

data = with open('write_to_file.txt') as f:    data=list(eval(f.readline()))

CodePudding user response:

Checkout chain.from_iterable from itertools, this method chaines up all the iterables within a iterable. So in this case, we don't even need to do looping.

Also checkout the documents for print function. There are several interesting arguments. You can set the separator with sep argument, and write to file with file argument.

result_list = [[{'head': 'Netgear','type': 'product or material produced',
'tail': 'smarten up an old TV'}], 
[{'head': 'Dirty and Coating Defects',
'type': 'subclass of',
'tail': 'Coating Defects'}]]

from itertools import chain

with open('write_to_file.txt', 'w ') as f:
    print(*(chain.from_iterable(result_list)), sep=", ", file=f)

To read the data written into the write_to_file.txt file,

with open('write_to_file.txt') as f:
    data = list(eval(f.readline()))

print(data)

result is

[{'head': 'Netgear',
  'type': 'product or material produced',
  'tail': 'smarten up an old TV'},
 {'head': 'Dirty and Coating Defects',
  'type': 'subclass of',
  'tail': 'Coating Defects'}]
  • Related