繁体   English   中英

Python-如何为while循环的迭代在文本文件中写新行?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM