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

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




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.