python - 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 循环中打开和关闭文件之外,有没有办法在每次迭代后写入它?
解决方案
这是由于没有发生冲洗。想写flush()
就写。此外,该with
构造可以在处理文件时为您提供帮助:
with open(..) as f:
f.write...
... when you leave the with block your file is written and closed for you
推荐阅读
- c# - 在 For 循环中运行的异步任务:System.ArgumentOutOfRangeException
- j - 在 J 中,我们如何生成来自具有指定均值和方差的正态分布的数字列表
- python - 使用 Telebot 检索任何用户的 ID
- r - 用R中的中位数替换用逗号分隔的数字字符串
- python - Pandas 数据框多索引索引
- java - 如何使用 intent.setData() 更改系统设置?
- operating-system - 为什么写被认为是输入操作而读被认为是输出操作?
- javascript - 谷歌脚本 - 通过电子邮件发送表格,其中包含来自循环的值
- yaml - 使用别名和 yamlordereddictloader 加载程序时未保留 YAML 映射顺序
- amazon-web-services - 如何使用 apache camel 以 json 格式发送从 aws s3 下载的文件的内容?