我试图创建一个日志文件来捕获while循环每次迭代的输出,但是我似乎只能捕获倒数第二行,并在该行下创建一个空白的新行。你知道吗
我有这个密码:
from glob import glob
import task_prep
import time
import datetime
path = glob('F:\\Transcoder\\staging\\prep\\*.xml')
while len(path) >= 0:
log = open('log_file.txt', 'w')
if int(len(path)):
data = (str(datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")) + ': files')
print(data)
log.write(data + '\n')
task_prep.task_prep()
path = glob('F:\\Transcoder\\staging\\prep\\*.xml')
time.sleep(3)
else:
data = (str(datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")) + ': no files')
print(data)
log.write(data + '\n')
path = glob('F:\\Transcoder\\staging\\prep\\*.xml')
time.sleep(3)
这只是覆盖第一行上写的所有内容,但是打印出来的是:
2016-12-06 10:25:56: no files
2016-12-06 10:25:59: no files
2016-12-06 10:26:02: no files
2016-12-06 10:26:05: no files
2016-12-06 10:26:08: no files
2016-12-06 10:26:11: no files
2016-12-06 10:26:14: no files
2016-12-06 10:26:17: no files
2016-12-06 10:26:20: no files
2016-12-06 10:26:23: no files
2016-12-06 10:26:26: no files
Process finished with exit code 1
这是写入文本文件的内容:
2016-12-06 10:26:23: no files
第一行是一根绳子,下面是一根新线。你知道吗
我做错什么了?你知道吗
在文件中的位置0处的每个循环转弯处打开文件,因此会覆盖上一个结果。你知道吗
必须在
while
块之前打开文件,才能保留内存中的前一个位置:奖金:这里,我使用
with
,它使用在open
中实现的上下文管理器。文件将在with
块结束后自动关闭。你知道吗您也可以使用
'a'
模式(用于append),但是仍然会多次打开文件,这是非常低效的。你知道吗相关问题 更多 >
编程相关推荐