-1

Okay, I have a program that outputs tuples containing integers and appends them to a list like this:

[(0,98,7), (437, 563, 128), (82, 45, 221)...]

I'm wanting to write the tuples to a file with the .write() function like this with "values" as the list the tuples are stored in:

output=open("output.txt","w")
for v in range(len(values)):
    print(values[v]) #so it prints each value in the shell for error check
    output.write(values[v])

The expected result is a text file with its contents like this:

0,98,7
437, 563, 128
82, 45, 221
...

The problem is that it says it can't write a tuple to a file; it asks for a string. I've tried to use the .join() function and the list() function to try to change the tuple either to a string or a list within the values list. Does anyone know how I could solve this issue? Thanks so much.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • What was the code you used with the `join` and what was the error that prevented it from working? Also, please consider using `with open('output.txt', 'w') as output_file:...`, it is safer because it closes files even if there is an error – darthbith Feb 25 '17 at 01:38
  • 1. Use `for v in values:`. 2. Maybe this `output.write(str(v))`. 3. Don't forget to close the file (at the end). – Elmex80s Feb 25 '17 at 01:38
  • Thank you all who helped me on this; I guess I was looking in the wrong place and got the wrong answers...I'm relatively familiar with python and never read about the CSV module. Thanks so much; the information is very useful! – Diamond Heart Feb 25 '17 at 02:38

2 Answers2

3

This is exactly what the csv module is made for:

import csv

with open('output.txt','w',newline='') as fou:
  cw = csv.writer(fou)
  cw.writerows(values)
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
1

Seeing as how someones already shown the csv way, here it is without.

s = [(0,98,7), (437, 563, 128), (82, 45, 221)]
with open('out.txt', 'w') as f:
    for e in s:
        f.write('%s\n' % ','.join(str(n) for n in e))

Just write em out in a loop. Each element in the collection passed to join should be a string so convert each value then use join make the comma separated lines.

Result

ubuntu@ubuntu:~$ cat out.txt
0,98,7
437,563,128
82,45,221

Note you dont consistently have spaces after the commas in your output. If made my outout like the first line, without them. If you want them just change your joining string ','.join(etc...) => ', '.join(etc...)

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61