0

I have a problem with writing my printed output to a file.

My code:

list1 = [2,3]
list2 = [4,5]
list3 = [6,7]

for (a, b, c) in zip(list1, list2, list3):
    print a,b,c

the output I get is:

>>> 
2 4 6
3 5 7
>>> 

but I have problems with saving this output, I tried:

fileName = open('name.txt','w')
for (a, b, c) in zip(list1, list2, list3):
    fileName.write(a,b,c)

and various combinations like fileName.write(a+b+c) or (abc), but I am unsuccessful...

Cheers!

4 Answers 4

1

The problem is that the write method expects a string, and your giving it an int.

Try using format and with:

with open('name.txt','w') as fileName:
    for t in zip(list1, list2, list3):
        fileName.write('{} {} {}'.format(*t))
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, this seem to work! I just have to figure out how to add the spaces between the lines, any tips?
0

How about using a format string:

fileName.write("%d %d %d" % (a, b, c))

Comments

0

Use with. Possibly your file handle is not closed, or flushed correctly and so the file is empty.

list1 = [2,3]
list2 = [4,5]
list3 = [6,7]

with open('name.txt', 'w') as f:
    for (a, b, c) in zip(list1, list2, list3):
        f.write(a, b, c)

You should also note that this will not create new lines at the end of each write. To have the contents of the file be identical to what you printed, you can use the following code (choose one write method):

with open('name.txt', 'w') as f:
    for (a, b, c) in zip(list1, list2, list3):
        # using '%s' 
        f.write('%s\n' % ' '.join((a, b, c)))
        # using ''.format()
        f.write('{}\n'.format(' '.join((a, b, c))))

4 Comments

Hi, unfortunately I get an error here: f.write(a, b, c) TypeError: function takes exactly 1 argument (3 given)
That is because I told you not to do it that way. Please use the second part of my answer.
I tried the second part as well," f.write('%s\n' % ' '.join(a, b, c)) TypeError: join() takes exactly one argument (3 given)"
Sorry, that is my fault, forgot a pair of parenthesis, copy the new version and try again.
0

You can use the print >> file syntax:

with open('name.txt','w') as f:
    for a, b, c in zip(list1, list2, list3):
        print >> f, a, b, c

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.