当我在文件中写入一个元组时,在控制台中打印它时我丢失了一些值

时间:2019-05-09 16:03:21

标签: python list tuples

我有这个元组

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编写代码

1 个答案:

答案 0 :(得分:1)

您需要在循环结束时关闭文件,以确保将输出缓冲区刷新到文件中。

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

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