[英]Python - How do you write a new line in a text file for ever iteration of a while loop?
我試圖創建一個日志文件來捕獲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
第1行有一個字符串,下面有一個新行。
我究竟做錯了什么?
您在每個循環回合中打開文件的位置為文件的0,因此將覆蓋先前的結果。
您必須在while
塊之前打開文件,以將先前位置保留在內存中:
from glob import glob
import task_prep
import time
import datetime
path = glob('F:\\Transcoder\\staging\\prep\\*.xml')
with open('log_file.txt', 'w') as log:
while len(path) >= 0:
if int(len(path)):
data = (str(datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")) + ': files')
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')
log.write(data + '\n')
path = glob('F:\\Transcoder\\staging\\prep\\*.xml')
time.sleep(3)
獎勵 :在這里,我使用with
來利用open
實現的上下文管理器。 with
塊結束后,文件將自動關閉。
您也可以使用'a'
模式(用於附加),但是您仍然會多次打開文件,效率非常低下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.