Reputation: 371
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!
Upvotes: 0
Views: 285
Reputation: 97571
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
Upvotes: 0
Reputation: 6828
The problem is that the write
method expects a string
, and your giving it an int
.
with open('name.txt','w') as fileName:
for t in zip(list1, list2, list3):
fileName.write('{} {} {}'.format(*t))
Upvotes: 1
Reputation: 43447
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))))
Upvotes: 0
Reputation: 409166
How about using a format string:
fileName.write("%d %d %d" % (a, b, c))
Upvotes: 0