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

2024-04-27 16:05:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个日志文件来捕获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

第一行是一根绳子,下面是一根新线。你知道吗

我做错什么了?你知道吗


Tags: pathnoimportlogtaskdatadatetimetime
1条回答
网友
1楼 · 发布于 2024-04-27 16:05:31

在文件中的位置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'模式(用于append),但是仍然会多次打开文件,这是非常低效的。你知道吗

相关问题 更多 >