猿问

将计时器添加到此脚本中的这些文件中的 1 个

我有 2 个文件同时打印在同一行。我想将 time.sleep() 添加到 1 个文本文件中。我想延迟此脚本中 1 个文本文件与其他 1 个文本文件打印的时间。我想让文件创建新行,而不是在它们都打印时打印相同的组合。在哪里添加 time.sleep()?


from itertools import izip_longest

import time


with open("file1") as textfile1, open("file2") as textfile2:

for x, y in izip_longest(textfile1, textfile2, fillvalue=""):

    x = x.strip()

    y = y.strip()

    print("{0}{1}".format(x, y))


温温酱
浏览 106回答 2
2回答

扬帆大鱼

您只能打印 x(不带换行符),然后休眠并打印 y。Python 2 解决方案:import timefrom itertools import izip_longestimport syswith open("file1") as textfile1, open("file2") as textfile2:    for x, y in izip_longest(textfile1, textfile2, fillvalue=""):        x = x.strip()        sys.stdout.write("{0}".format(x))        sys.stdout.flush()        time.sleep(1)        y = y.strip()        sys.stdout.write("{0}".format(y))        sys.stdout.write("\n")        sys.stdout.flush()Python 3 解决方案from itertools import zip_longestimport timewith open("file1") as textfile1, open("file2") as textfile2:    for x, y in zip_longest(textfile1, textfile2, fillvalue=""):        x = x.strip()        print("{0}".format(x), end='')        time.sleep(1)        y = y.strip()        print("{0}".format(y))

人到中年有点甜

目前尚不清楚你想要什么,但我想它是这样的#! /usr/bin/env python3from rx import from_, interval, merge, zipfrom rx.scheduler import ThreadPoolSchedulerpool = ThreadPoolScheduler(10)f1 = from_(open('f1.txt'))f2 = from_(open('f2.txt'))o1 = merge(    f1,    zip(interval(1.0), f2)    )o1.subscribe(print, scheduler=pool)o1.run()它使用RxPy。并且像这样工作:为文件 1 创建 observable为文件 2 创建 observable创建另一个合并 f1 和 f2 的 observable,它以 1 秒的间隔发射订阅和打印等到它完成
随时随地看视频慕课网APP

相关分类

Python
我要回答