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

Here, we are writing a Python program that will print lines of files with a delay in printing.
Submitted by Shivang Yadav, on February 21, 2021

Python sleep() function -delay in Python program

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.

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. 

Python file handling programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.