![](/img/trans.png)
[英]how to read a specific line and print a specific position in this line using python
[英]How to print a file line by line in specific interval continuously using python?
我有一個包含4個網站名稱的文件,如下所示。 我想在特定的時間間隔內連續打印每個網站名稱。
sample.txt的:
facebook.com
gmail.com
test.com
yahoo.com
我試過以下代碼。 但它的印刷網站只命名一次。 我想繼續網站名稱。
from time import sleep
while True:
with open ("sample.txt", 'r') as test:
while True:
print test.readline()
sleep(3)
pass
預期產量:
facebook.com
gmail.com
test.com
yahoo.com
facebook.com
gmail.com
test.com
yahoo.com
facebook.com
gmail.com
test.com
yahoo.com
facebook.com
gmail.com
test.com
yahoo.com
.
.
.
我可以幫忙解決這個問題嗎?
謝謝。
你只需要遍歷每一行:
for line in test:
print line
而不是True:
完成:
from time import sleep
with open ("sample.txt", 'r') as test:
for line in test
print line
sleep(3)
在第一輪調用readline()
之后,返回迭代器的文件對象已經耗盡。 您應該將整個文件讀入列表並連續迭代該列表。
from time import sleep
with open ("sample.txt") as test:
lines = test.readlines() # read all lines into list
while True:
for line in lines:
print line
sleep(3)
問題是,在readline()
到達文件末尾后,它將繼續返回空行。 您需要一些結束循環的東西,以便您可以從文件的開頭重新開始:
from time import sleep
while True:
with open ("sample.txt", 'r') as test:
for line in test:
print line.rstrip()
sleep(3)
如果你真的想使用readline
,那么你需要測試文件的結尾。 當readline
正在讀取實際行時,它將始終返回至少一個換行符。 如果它什么也沒有返回,那么它已到達文件的末尾。 從而:
from time import sleep
while True:
with open ("sample.txt", 'r') as test:
while True:
line = test.readline()
if not line:
break
print line.rstrip()
sleep(3)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.