Title: Save list without square brackets to a file
Tags: python;string;list;loops;for-loop
Question: 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 =&quot;, &quot;)
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://151.154.11.224: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()))
Comment: if you don't want the last comma to appear then use `sep` in place of `end`.

Here is the accepted answer: 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=&quot;, &quot;, 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'}]
Comment for this answer: For the edited example, if I understand this correctly, you can get the data read back in by `with open('written_to_file.txt') as f:    data=list(eval(f.readline()))`
Comment for this answer: But keep in mind that this is not a good practice to write data into python representation text and read it right back in. You should consider much more robust options like json file, csv file, or even better, using databases.
Comment for this answer: @Timskouten check out the edited answer please, comments section messed up with the indentation
Comment for this answer: You're welcome. I mainly work with pandas and apache spark. Some optimization on loops I may be able to help. But feel free to post more questions! There're many helpful experts on stackoverflow.
Comment for this answer: Thank you so much for your answer! However, in case that I want to input this text into a variable/function, as mentioned in the edited code above. Do you have any idea how this can be adjusted? The code after the # shows the format how the data should be read in. Thanks in advance!
Comment for this answer: I adjusted the code according to your recommendation. It unfortunately does not seem to work. Is this the correct order as you recommended? However, I will try to do it through a Json method as well.
Comment for this answer: This worked out! Thanks so much!! Are you by accident also specialized in working with spacy / for loops?
Comment for this answer: Great, thanks for your prompt and helpful responses! I yesterday uploaded another question, please see the following link: https://stackoverflow.com/questions/72978882/pass-elements-of-a-list-in-a-function-spacy-pipeline-version In case that you have any knowledge on this topic, please let me know. Or if you may know someone who could help out on this topic. Kind regards!


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2022:00:07/15/22', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<python><string><list><loops><for-loop>', 'Title': 'Save list without square brackets to a file', 'ViewCount': 55, 'id': 72992127, 'user_AboutMe': None, 'user_AccountId': 23325824.0, 'user_DisplayName': 'Timskouten', 'user_Reputation': 41.0, 'user_Views': 7.0, 'user_id': 19495942.0}}