I have a list that looks like this
list_geo = [[5], ['Optimized energy: -39.726863484331 E_h'],
['C\t', '-1.795202\t', ' 0.193849\t', ' 0.019437'],
['H\t', '-0.728046\t', '0.337237\t', ' 0.135687'],
['H\t', '-2.044433\t', '-0.840614\t', ' 0.220592'],
['H\t', '-2.085087\t', ' 0.444715\t', '-0.993886'],
['H\t', '-2.323267\t', ' 0.834105\t', ' 0.714902']]
I want to write this to file outputfile
, and I tried to use
with open(outputfile, "w") as output_file:
output_file.write(list_geo)
But this does not work. Joining list_geo
also does not work. How can I save this?
I guess want to write every sublist of your list as one line.
Then this is what you need:
Content of
file.txt
after running the script:Explanation:
"".join()
takes a list of strings and just concatenates them together without spaces in between[str(i) for i in line]
converts every element in the list into string (needed only because you have the[5]
as the first sublist in your list)If you want to add formatting to your lines you better have the values as real numbers first, i.e. instead of
['C\t', '-1.795202\t', ' 0.193849\t', ' 0.019437']
you'd need['C', -1.795202, 0.193849, 0.019437]
and then format them with e.g."{}\t{:>9f}\t{:>9f}\t{:>9f}\n".format(*line)
.If you somehow just get this list from a dirty source you cannot change, then you'd need to preprocess the line somehow, e.g. like this:
Which results in:
You can't write a list directly to file, but you can write a string/stream of characters.
Convert your list into a string and then write the string to the file
You need to use for loop