将打印输出写入文件(python)

将打印输出写入文件(python),python,output,Python,Output,我在将打印输出写入文件时遇到问题 我的代码: list1 = [2,3] list2 = [4,5] list3 = [6,7] for (a, b, c) in zip(list1, list2, list3): print a,b,c 我得到的结果是: >>> 2 4 6 3 5 7 >>> 但我在保存此输出时遇到问题,我尝试: fileName = open('name.txt','w') for (a, b, c) in zip(li

我在将打印输出写入文件时遇到问题

我的代码:

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

for (a, b, c) in zip(list1, list2, list3):
    print a,b,c
我得到的结果是:

>>> 
2 4 6
3 5 7
>>> 
但我在保存此输出时遇到问题,我尝试:

fileName = open('name.txt','w')
for (a, b, c) in zip(list1, list2, list3):
    fileName.write(a,b,c)
还有各种组合,如fileName.write(a+b+c)或(abc),但我没有成功


干杯

使用格式字符串怎么样:

fileName.write("%d %d %d" % (a, b, c))
问题是该方法需要一个
字符串
,而您给它一个
int

尝试使用和:


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

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):
        print >> f, a, b, c

嗨,不幸的是,我在这里遇到了一个错误:f.write(a,b,c)TypeError:函数只接受1个参数(给定3个),这是因为我告诉过你们不要这样做。请使用我答案的第二部分。我也尝试了第二部分,“f.write('%s\n''%1!'.join(a,b,c))类型错误:join()只接受一个参数(给定3个)”抱歉,这是我的错误,忘记了一对括号,复制新版本,然后重试。谢谢,这似乎有效!我只是想知道如何在两行之间添加空格,有什么建议吗?
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))))
with open('name.txt','w') as f:
    for a, b, c in zip(list1, list2, list3):
        print >> f, a, b, c