首页 > 解决方案 > Python 什么时候真正写入文件?

问题描述

我有一个 python 脚本,它收集用户输入并将它们写入文件。基本结构是代码遍历图像列表,向用户显示每个图像,通过输入提示用户,并通过循环记录每次迭代的用户输入。在循环中写入很重要,因为文件列表有数千个,我不想因为错误或电源故障或其他原因而重新启动。

代码方面,相关部分是:

f=open(outfile,a,newline='')
for i in range(0,numFiles):
    folder = sheet.cell_value(i,22) #get image location from a spreadsheet
    Assess = sheet.cell_value(i,23) #get the current assessment from the spreadsheet
    if len(Assess)==0: #no existing assessment
       impath=os.path.join(folder,'image.png')
       <plt calls to show figure>
       while len(Assess)==0:
           Assess=input('Enter Assessment for row %d:' % i)
       <close figure>
    f.write('%s,'%s\n' % (folder, Assess.upper())) 
f.close()

电子表格已经有前 70 行的数据,所以我第一次得到输入查询是在 i=71 上。我已经通过对该input行的多次调用来运行它,但是当我在记事本中打开文件时(代码仍在运行时),我只看到 71 个值是在未输入if len(Assess)==0:. 我能够让我的手动输入在文件中可见的唯一方法是关闭文件。

为什么文件写入对写入的处理Assess=input()Assess=sheet.cell_value()?

除了在 for 循环中打开和关闭文件之外,有没有办法在每次迭代后写入它?

标签: pythontimingwrite

解决方案


这是由于没有发生冲洗。想写flush()就写。此外,该with构造可以在处理文件时为您提供帮助:

   with open(..) as f:
       f.write...
   
   ... when you leave the with block your file is written and closed for you

推荐阅读