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

4 回答 4

1

问题是该write方法需要 a string,而您给它一个int.

尝试使用formatwith

with open('name.txt','w') as fileName:
    for t in zip(list1, list2, list3):
        fileName.write('{} {} {}'.format(*t))
于 2013-04-24T11:39:00.273 回答
0

如何使用格式字符串:

fileName.write("%d %d %d" % (a, b, c))
于 2013-04-24T11:38:44.450 回答
0

您可以使用以下print >> file语法:

with open('name.txt','w') as f:
    for a, b, c in zip(list1, list2, list3):
        print >> f, a, b, c
于 2013-04-24T19:31:38.827 回答
0

使用with. 可能您的文件句柄未关闭或未正确刷新,因此文件为空。

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)

您还应该注意,这不会在每次写入结束时创建新行。要使文件的内容与您打印的内容相同,您可以使用以下代码(选择一种写入方法):

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))))
于 2013-04-24T11:39:16.310 回答