我正在编写一个支持线程的python程序,它可以读取文件并发送,但有没有办法让程序一次读取并发送N行数?
from random import randint
import sys
import threading
import time
def function():
fo = open("1.txt", "r")
print "Name of the file: ", fo.name
while True:
line = fo.readlines()
for lines in line:
print(lines)
fo.seek(0, 0)
time.sleep(randint(1,3))
game = threading.Thread(target=function)
game.start()
以下python代码只能让我一次发送一行,然后回放。
答案 0 :(得分:1)
如果您遵循代码逻辑,在for
循环中迭代文件中的行,则在打印后立即将文件指针重置为第一行。这就是你打印第一行的原因。要获得随机数量的打印线,您可以通过多种方式实现,例如:
def function():
fo = open("1.txt", "r")
print "Name of the file: ", fo.name
lines = fo.readlines() # changed the var names, lines vs. line
start_index = 0
while True:
length = randint(1, len(lines)-start_index)
for line in lines[start_index:start_index+length]:
print(line)
start_index += length
time.sleep(randint(1,3))
在那里,在将文件内容读入lines
之后,代码将在每一行上循环,但只到第n个索引,通过randint(1, len(lines))
计算,并避免{{1}所以至少你会打印一行。在打印循环之后,我们重置文件指针,然后休眠。
修订:给定新的细节,在每个周期,我们现在随机化要打印的线条窗口,同时沿着已打印的线条移动。基本上是每次迭代时随机长度的滑动窗口,确保它(应该)与数组的大小一致。根据需要进行调整。
答案 1 :(得分:1)
这样的事情?
from random import randint
import sys
import threading
import time
def function():
fo = open("1.txt", "r")
print "Name of the file: ", fo.name
lines = fo.readlines()
while lines:
toSend = ""
for i in range(0,random.randint(x,y)): #plug your range in
toSend += lines.pop(0)
print(toSend)
game = threading.Thread(target=function)
game.start()