0% found this document useful (0 votes)
2 views7 pages

Advaitha Python 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views7 pages

Advaitha Python 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Course Code & Name : 21CS15IT –PROBLEM SOLVING

PYTHON PROGRAMMING
Assignment Topic : Program to read a random line from a file
Assignment Batch No. : 02
Student Name : Advaitha Sai Kumar
VH No./ Reg. No. : Vh - 13952
Year/Sem :I/I
Batch : 2024-28
Academic Year : 2024-25
Dept. & Section : B.Tech Ai & Ds - A
WRITE A PYTHON PROGRAM TO READ A
RANDOM LINE FROM A FILE.
ALGORITHM

1.The algorithm to read a random line from a file can be summarized as


follows:Open the file in read mode.
2.Read all lines from the file into a list.
3.Check if the list is empty:If empty, print an error message.
4.Use a random function to select an index from the list of lines.
5.Return or print the line at the selected index.
6.Close the file.
PSEUDOCODE
PYTHON PROGRAM OF RANDOM LINE
KEY COMMANDS USED :
•open(file_path, 'r'): Opens the specified file in read mode.
•file.readlines(): Reads all lines from the file and stores them in a list.
•random.choice(lines): Selects a random element from the list of lines.
•strip(): Removes any leading or trailing whitespace from the selected
line.
•Exception handling (try, except) ensures that errors like missing files are
managed gracefully.

This program effectively demonstrates how to read a random


line from a text file using Python while maintaining clarity and
efficiency in memory usage.
OUTPUT OF PROGRAM

PICKING UP A RANDOM LINE FROM THE


OUTPUT :

You might also like