当我在文件中编写元组时,我会在控制台打印时失去一些值,我会全部得到它们



我有这个元组

tuple=[(1,0.1),(2,0.2)...(714,7,14)] etc

当我使用打印(元组(时,我会进入控制台,我期望的

[(1,0.1),(2,0.2)...(100,1)]

当我尝试一下时:

for counter in range (0,100): 
 file.write('{}'.format(tuple))

我在一个.txt文件中也得到了我的期望。

但是,当我尝试按线打印元组时,请使用以下方式:

for j in tuple:
 file.write(' '.join(str(s) for s in j) + 'n')

它并没有写所有元组,而是在其末尾失去了一些值。在这种方法上也发生了同样的事情:

for counter in range (0,100):
 file.write('{}'.format(Result[counter])) 

我使用Anaconda的Python 3.7我在Spyder

中写我的代码

您需要在循环末端关闭文件,以确保输出缓冲区被冲入文件。

使用上下文管理器确保这一点:

with open("filename", "w") as file:
    #any for loop that writes to the file

最新更新