Skip to content

Commit 972e1bc

Browse files
authored
Merge pull request sumanth-0#812 from aniruddhaadak9/aniruddhaadak9-patch-1
Add Random File Content Picker - Fixes sumanth-0#790
2 parents 5604180 + 03dc256 commit 972e1bc

File tree

2 files changed

+253
-0
lines changed

2 files changed

+253
-0
lines changed
Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
# Random File Content Picker
2+
3+
## Description
4+
5+
A Python script that randomly selects and displays lines from a text file. Perfect for displaying random quotes, daily tasks, motivational messages, or any line-based content.
6+
7+
## Features
8+
9+
- 📝 Pick one or multiple random lines from any text file
10+
- 🎲 Each run produces a different random selection
11+
- 🔢 Optional line numbering for output
12+
- 🛡️ Comprehensive error handling
13+
- ⚡ Command-line interface for easy usage
14+
- 📁 Works with any UTF-8 encoded text file
15+
16+
## Installation
17+
18+
No additional dependencies required! This script uses only Python standard library modules.
19+
20+
```bash
21+
# Clone the repository
22+
git clone https://github.com/sumanth-0/100LinesOfPythonCode.git
23+
cd 100LinesOfPythonCode/snippets/random_file_content_picker
24+
```
25+
26+
## Usage
27+
28+
### Basic Usage
29+
30+
Pick a single random line from a file:
31+
32+
```bash
33+
python random_file_content_picker.py quotes.txt
34+
```
35+
36+
### Pick Multiple Lines
37+
38+
Select multiple random lines at once:
39+
40+
```bash
41+
python random_file_content_picker.py quotes.txt --count 3
42+
```
43+
44+
### Show Line Numbers
45+
46+
Display line numbers with the output:
47+
48+
```bash
49+
python random_file_content_picker.py quotes.txt --numbered
50+
```
51+
52+
### Combined Options
53+
54+
Combine multiple options:
55+
56+
```bash
57+
python random_file_content_picker.py tasks.txt -c 5 -n
58+
```
59+
60+
## Command-Line Arguments
61+
62+
- `filename` (required): Path to the text file to read from
63+
- `-c, --count`: Number of random lines to pick (default: 1)
64+
- `-n, --numbered`: Show line numbers with output
65+
- `-h, --help`: Display help message
66+
67+
## Example
68+
69+
Create a sample quotes file:
70+
71+
```bash
72+
echo "The only way to do great work is to love what you do. - Steve Jobs" >> quotes.txt
73+
echo "Innovation distinguishes between a leader and a follower. - Steve Jobs" >> quotes.txt
74+
echo "Stay hungry, stay foolish. - Steve Jobs" >> quotes.txt
75+
echo "Life is what happens when you're busy making other plans. - John Lennon" >> quotes.txt
76+
echo "The future belongs to those who believe in the beauty of their dreams. - Eleanor Roosevelt" >> quotes.txt
77+
```
78+
79+
Then run:
80+
81+
```bash
82+
python random_file_content_picker.py quotes.txt --count 2 --numbered
83+
```
84+
85+
Output:
86+
```
87+
============================================================
88+
Random pick from: quotes.txt
89+
============================================================
90+
91+
1. Innovation distinguishes between a leader and a follower. - Steve Jobs
92+
2. Life is what happens when you're busy making other plans. - John Lennon
93+
94+
============================================================
95+
```
96+
97+
## Use Cases
98+
99+
- 💡 **Daily Motivation**: Display random motivational quotes
100+
-**Task Randomizer**: Randomly select tasks from a to-do list
101+
- 📚 **Learning Tool**: Pick random vocabulary words or study topics
102+
- 🎮 **Game Ideas**: Select random game prompts or challenges
103+
- 🍽️ **Meal Planner**: Choose random recipes for the week
104+
- 💭 **Writing Prompts**: Get random creative writing ideas
105+
106+
## Error Handling
107+
108+
The script handles various error scenarios:
109+
110+
- File not found
111+
- Permission denied
112+
- Empty files
113+
- Invalid encoding
114+
- Invalid count values
115+
116+
## Requirements
117+
118+
- Python 3.6 or higher
119+
- No external dependencies
120+
121+
## Contributing
122+
123+
Feel free to submit issues, fork the repository, and create pull requests for any improvements.
124+
125+
## License
126+
127+
This project is open source and available under the MIT License.
128+
129+
## Author
130+
131+
Created as part of the 100 Lines of Python Code project.
132+
133+
## Related Issue
134+
135+
This implementation addresses [Issue #790](https://github.com/sumanth-0/100LinesOfPythonCode/issues/790) - Random File Content Picker
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Random File Content Picker
4+
5+
This script reads a file and randomly selects a line from it.
6+
Useful for displaying random quotes, tasks, tips, or any line-based content.
7+
8+
Usage:
9+
python random_file_content_picker.py <filename>
10+
python random_file_content_picker.py <filename> --count <number>
11+
"""
12+
13+
import random
14+
import sys
15+
import os
16+
import argparse
17+
from pathlib import Path
18+
19+
20+
def read_file_lines(filename):
21+
"""
22+
Read all non-empty lines from a file.
23+
24+
Args:
25+
filename (str): Path to the file to read
26+
27+
Returns:
28+
list: List of non-empty lines from the file
29+
30+
Raises:
31+
FileNotFoundError: If the file doesn't exist
32+
PermissionError: If the file can't be read
33+
"""
34+
try:
35+
with open(filename, 'r', encoding='utf-8') as file:
36+
lines = [line.strip() for line in file if line.strip()]
37+
return lines
38+
except FileNotFoundError:
39+
print(f"Error: File '{filename}' not found.")
40+
sys.exit(1)
41+
except PermissionError:
42+
print(f"Error: Permission denied to read '{filename}'.")
43+
sys.exit(1)
44+
except UnicodeDecodeError:
45+
print(f"Error: Unable to decode '{filename}'. Please ensure it's a text file.")
46+
sys.exit(1)
47+
48+
49+
def pick_random_lines(lines, count=1):
50+
"""
51+
Pick random line(s) from a list of lines.
52+
53+
Args:
54+
lines (list): List of lines to choose from
55+
count (int): Number of lines to pick
56+
57+
Returns:
58+
list: List of randomly selected lines
59+
"""
60+
if not lines:
61+
print("Error: The file is empty or contains only whitespace.")
62+
sys.exit(1)
63+
64+
if count > len(lines):
65+
print(f"Warning: Requested {count} lines but file only has {len(lines)} lines.")
66+
count = len(lines)
67+
68+
return random.sample(lines, count) if count > 1 else [random.choice(lines)]
69+
70+
71+
def main():
72+
"""
73+
Main function to parse arguments and display random lines.
74+
"""
75+
parser = argparse.ArgumentParser(
76+
description='Pick random lines from a text file',
77+
epilog='Example: python random_file_content_picker.py quotes.txt --count 3'
78+
)
79+
parser.add_argument('filename', help='Path to the text file')
80+
parser.add_argument(
81+
'-c', '--count',
82+
type=int,
83+
default=1,
84+
help='Number of random lines to pick (default: 1)'
85+
)
86+
parser.add_argument(
87+
'-n', '--numbered',
88+
action='store_true',
89+
help='Show line numbers with output'
90+
)
91+
92+
args = parser.parse_args()
93+
94+
# Validate count
95+
if args.count < 1:
96+
print("Error: Count must be at least 1.")
97+
sys.exit(1)
98+
99+
# Read file and pick random lines
100+
lines = read_file_lines(args.filename)
101+
selected_lines = pick_random_lines(lines, args.count)
102+
103+
# Display selected lines
104+
print(f"\n{'='*60}")
105+
print(f"Random pick from: {Path(args.filename).name}")
106+
print(f"{'='*60}\n")
107+
108+
for i, line in enumerate(selected_lines, 1):
109+
if args.numbered:
110+
print(f"{i}. {line}")
111+
else:
112+
print(line)
113+
114+
print(f"\n{'='*60}\n")
115+
116+
117+
if __name__ == "__main__":
118+
main()

0 commit comments

Comments
 (0)