Q:

Python program to delay printing of lines from a file using sleep function

belongs to collection: Python file handling programs

0

In this program, we will use the concept of file handling and time.

File handling is very important and error-prone in any web application. It is quite easy to have a resource leakage with files if the file reading or writing is not gracefully closed.

It is used to read data line by line.

Time module is a built-in module in Python and it has various functions that require it to perform more operations on time. It is used to delay the printing of lines using the sleep method.

Algorithm:

  • Step 1: Import the time module.
  • Step 2: Open the file in 'r' mode for reading.
  • Step 3: Use the read method to read file contents.
  • Step 4: Print each line of the input and then use time.sleep() method to delay the printing.
  • Step 5: Close the file using close() method.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Python program to delay printing of line from a file using sleep function

import time

F=open("drinks.dat","r")

while(True):
    b=F.read(1)
    if(b==""):
        break
    print(b,end="")
    time.sleep(0.3)

F.close()

File : drinks.dat

RedBull
Cafe Mocha
Americano
Coca Cola
Tea 

Output:

RedBull
Cafe Mocha
Americano
Coca Cola
Tea 

*each line will be delayed. 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python program to count the number of lines in a f... >>
<< Read a program from another file in Python...