0

I have a long string of values in text file

[(3.7811269080692846, 0, 1), (3.7811269080692846, 1, 0), (3.7698643400208622, 1, 2), (3.7698643400208622, 2, 1)]

And I wish to print every parenthetical on a separate line in the format like this

[(3.7811269080692846, 0, 1), 
(3.7811269080692846, 1, 0), 
(3.7698643400208622, 1, 2), 
(3.7698643400208622, 2, 1)]

Here is how I print this to the file

f = open('contact.txt', 'w')

f.write(str(z))

f.close()

What would be an easy way to print the file in my desired format?

  • You must surely have tried something here? What happened? – roganjosh Jan 08 '19 at 00:15
  • 1
    `replace( "), ", "),\n" )` ... replace each end-of-element sequence with a properly inserted newline. – Prune Jan 08 '19 at 00:16
  • @Prune but it's not a string, it's a list – roganjosh Jan 08 '19 at 00:16
  • Oh, I'm confused. You actually want to _write_ to the file. I thought they were two different cases. The `replace()` method is prone to all sorts of errors and I wonder why you would want to write it like that in the first place; are you hoping to store an object to be remade later? – roganjosh Jan 08 '19 at 00:18
  • check this out https://stackoverflow.com/questions/1523660/how-to-print-a-list-in-python-nicely – fkajzer Jan 08 '19 at 00:20

3 Answers3

0

Here's a super lazy way to go about it:

obj = [(3.7811269080692846, 0, 1),
       (3.7811269080692846, 1, 0),
       (3.7698643400208622, 1, 2),
       (3.7698643400208622, 2, 1)]

with open(r"C:\Temp\test.txt", 'w') as f:
    f.write("[\r\n")
    for tup in obj:
        f.write(f"\t{tup!r},\r\n")
    f.write("]\r\n")

This will indent all your tuples with a tab and make sure everything has its own line.

Maximilian Burszley
  • 15,132
  • 3
  • 27
  • 49
0

This is one way to do it :

text = [(3.7811269080692846, 0, 1),
        (3.7811269080692846, 1, 0),
        (3.7698643400208622, 1, 2),
        (3.7698643400208622, 2, 1)]

with open('contact.txt', 'w') as f:
    for line in text:
        f.write("{}\n".format(str(line)))
Val F.
  • 1,019
  • 1
  • 7
  • 17
0

You can intent pprint (pretty print).

from pprint import pprint.

array=[some values]

pprint(array)
Egalicia
  • 516
  • 6
  • 14