Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:在写入下一行之前,有没有办法在输出文件中等待几秒钟?_Python_Python 3.x - Fatal编程技术网

Python:在写入下一行之前,有没有办法在输出文件中等待几秒钟?

Python:在写入下一行之前,有没有办法在输出文件中等待几秒钟?,python,python-3.x,Python,Python 3.x,为了绘制我不断写入的文件,有必要在代码写入输出文件的每一行之间进行一些暂停。否则,该文件将变成一个重文件,python在绘制它时会遇到麻烦 我已经尝试过time.sleep()了,但在文件中只有一行我想作为示例编写 Escribir = True my_file = open("testwrite.txt", "w") while Escribir: my_file.write("hola" + "\n") time.sleep(2) my_file.close 我预计产

为了绘制我不断写入的文件,有必要在代码写入输出文件的每一行之间进行一些暂停。否则,该文件将变成一个重文件,python在绘制它时会遇到麻烦

我已经尝试过time.sleep()了,但在文件中只有一行我想作为示例编写

Escribir = True

my_file = open("testwrite.txt", "w")

while Escribir:

    my_file.write("hola" + "\n")
    time.sleep(2)
my_file.close
我预计产量为 你好

你好

你好

每2秒换一条新线路,但我只得到一次Hola


祝你们今天愉快

您很可能在文件中看不到新的“hola”,因为它尚未从缓冲区刷新到文件中。要确保在继续之前已刷新,请使用
flush()


事实上,这就是问题所在。它非常有用。
Escribir = True

my_file = open("testwrite.txt", "w")

while Escribir:

    my_file.write("hola" + "\n")
    my_file.flush()
    time.sleep(2)
my_file.close()