2016-12-08 117 views
0

我有以下代码。我正在尝试使代码将打印保存到文件末尾的文件中。我会错过什么部分?打印到文件?

import itertools 

#Open test.txt 
file = open('test.txt', 'a') 

res = itertools.product('abcdef', repeat=3) # 3 is the length of your result. 
for i in res: 
    print ''.join(i) 
+0

有写作和实际的书面文件,打开该文件之间没有任何联系。 –

+0

在Python 2中,其中'print'是一个语句,您需要使用'print''.join(i)>> file'将输出定向到一个打开的文件。在Python 3中它的功能,使用'print(''。join(i),file = file)''。 – martineau

回答

3

你基本上没有与写入文件,如print打印输出到stdout默认为您的屏幕连接您的打印,但它是可以改变的,当然。

在我的示例中,我使用了with语句,这意味着文件将在其下面的代码完成执行后自动关闭,因此在完成处理时不需要记住关闭文件。

有关with您可以阅读here

你可以这样做的更多信息:

import itertools 

res = itertools.product('abcdef', repeat=3) # 3 is the length of your result. 
with open('test.txt', 'a') as f_output: 
    for i in res: 
     f_output.write(''.join(i)) 
     f_output.write('\n') 
+1

'以open()作为filevar:'是最佳实践。 – TemporalWolf