简体   繁体   English

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

[英]Python - How do you write a new line in a text file for ever iteration of a while loop?

I am trying to create a log file that captures the output of every iteration of a while loop, however I only seem to be able to capture the penultimate line and a create a blank new line under that. 我试图创建一个日志文件来捕获while循环的每次迭代的输出,但是我似乎只能捕获倒数第二行并在其下创建一个空白的新行。

I have this code: 我有以下代码:

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)

This is to just overwrite everything that's being written on the first line, however this is what gets printed: 这只是覆盖第一行中正在编写的所有内容,但这是打印出来的内容:

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

this is what gets written in the text file: 这是在文本文件中写入的内容:

2016-12-06 10:26:23: no files

A string on line 1 and a new line underneath. 第1行有一个字符串,下面有一个新行。

What am I doing wrong? 我究竟做错了什么?

You are opening the file at each loop turn, at the position 0 in the file, hence overwriting the previous result. 您在每个循环回合中打开文件的位置为文件的0,因此将覆盖先前的结果。

You have to open your file before the while block to keep the previous position in memory: 您必须在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)

Bonus : Here, I use with which makes the use of the context manager implemented in open . 奖励 :在这里,我使用with来利用open实现的上下文管理器。 The file will automatically be closed after the end of the with block. with块结束后,文件将自动关闭。

You could also use the 'a' mode (for append) but you will still open the file many times which is very inefficient. 您也可以使用'a'模式(用于附加),但是您仍然会多次打开文件,效率非常低下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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