Skip to content

Commit d7f9d04

Browse files
authored
Merge pull request sumanth-0#793 from akashadsare/add-random-file-content-picker
Add Random File Content Picker - Issue sumanth-0#790
2 parents 1aeacb6 + c0f9f58 commit d7f9d04

File tree

2 files changed

+212
-0
lines changed

2 files changed

+212
-0
lines changed
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
# Random File Content Picker 🎲📄
2+
3+
A simple Python script that chooses a random line from a file and prints it each time it runs. Perfect for daily quotes, random tasks, motivational messages, or any line-based content!
4+
5+
## Features
6+
7+
- **Random Line Selection**: Picks a random line from any text file
8+
- **Multiple Usage Modes**: Command line arguments or interactive input
9+
- **Sample Content**: Auto-creates sample quotes file if none provided
10+
- **Error Handling**: Graceful handling of missing files and permissions
11+
- **File Statistics**: Shows total number of lines in the file
12+
- **Clean Output**: Beautiful formatted display with emojis
13+
14+
## Usage
15+
16+
### Method 1: Interactive Mode
17+
```bash
18+
python random_file_picker.py
19+
```
20+
The script will prompt you for a file path, or create a sample quotes file if none provided.
21+
22+
### Method 2: Command Line Argument
23+
```bash
24+
python random_file_picker.py path/to/your/file.txt
25+
```
26+
27+
### Method 3: Use Sample File
28+
```bash
29+
python random_file_picker.py
30+
# Press Enter when prompted to use sample quotes
31+
```
32+
33+
## Example Output
34+
35+
```
36+
🎲 Random File Content Picker
37+
========================================
38+
39+
📂 Reading from: sample_quotes.txt
40+
41+
==================================================
42+
🎯 Random Pick:
43+
The only way to do great work is to love what you do. - Steve Jobs
44+
==================================================
45+
46+
📊 File contains 10 lines
47+
```
48+
49+
## File Format
50+
51+
The script works with any text file where each line contains content you want to randomly select from:
52+
53+
```
54+
Quote 1
55+
Quote 2
56+
Quote 3
57+
Task: Review project documentation
58+
Task: Update website content
59+
Remember to call mom
60+
```
61+
62+
## Use Cases
63+
64+
- **Daily Quotes**: Motivational or inspirational quotes
65+
- **Task Randomizer**: Random task selection from a to-do list
66+
- **Decision Maker**: Random choices from a list of options
67+
- **Learning Tool**: Random facts, vocabulary words, or study notes
68+
- **Creative Prompts**: Writing prompts or creative challenges
69+
- **Habit Tracker**: Random healthy habits or activities
70+
71+
## Requirements
72+
73+
- Python 3.6 or higher
74+
- No external dependencies (uses only Python standard library)
75+
76+
## Error Handling
77+
78+
The script handles various scenarios gracefully:
79+
- Missing files (offers to create sample file)
80+
- Empty files
81+
- Permission errors
82+
- Invalid file paths
83+
- Encoding issues
84+
85+
## Sample Content
86+
87+
If no file is provided, the script creates a sample file with 10 inspirational quotes from famous personalities.
88+
89+
## Customization
90+
91+
You can easily customize the script by:
92+
- Modifying the sample quotes in the `create_sample_file()` function
93+
- Changing the output format in the `main()` function
94+
- Adding filters for specific line patterns
95+
- Implementing weighted random selection
96+
97+
## Author
98+
99+
Created for issue #790 - 100 Lines of Python Code Project
100+
101+
## License
102+
103+
Open source - feel free to modify and enhance!
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
#!/usr/bin/env python3
2+
import random
3+
import os
4+
import sys
5+
6+
7+
def get_random_line(file_path):
8+
try:
9+
with open(file_path, 'r', encoding='utf-8') as file:
10+
lines = [line.strip() for line in file.readlines() if line.strip()]
11+
12+
if not lines:
13+
print("Error: The file is empty or contains no valid lines.")
14+
return None
15+
16+
return random.choice(lines)
17+
18+
except FileNotFoundError:
19+
print(f"Error: File not found: {file_path}")
20+
return None
21+
except PermissionError:
22+
print(f"Error: Permission denied: {file_path}")
23+
return None
24+
except Exception as e:
25+
print(f"Error reading file: {e}")
26+
return None
27+
28+
29+
def create_sample_file(file_path):
30+
"""Create a sample quotes file if it doesn't exist."""
31+
sample_quotes = [
32+
"The only way to do great work is to love what you do. - Steve Jobs",
33+
"Life is what happens to you while you're busy making other plans. - John Lennon",
34+
"The future belongs to those who believe in the beauty of their dreams. - Eleanor Roosevelt",
35+
"It is during our darkest moments that we must focus to see the light. - Aristotle",
36+
"The way to get started is to quit talking and begin doing. - Walt Disney",
37+
"Don't let yesterday take up too much of today. - Will Rogers",
38+
"You learn more from failure than from success. Don't let it stop you. - Unknown",
39+
"If you are working on something that you really care about, you don't have to be pushed. - Steve Jobs",
40+
"Experience is a hard teacher because she gives the test first, the lesson afterward. - Vernon Law",
41+
"Success is not final, failure is not fatal: it is the courage to continue that counts. - Winston Churchill"
42+
]
43+
44+
try:
45+
with open(file_path, 'w', encoding='utf-8') as file:
46+
for quote in sample_quotes:
47+
file.write(quote + '\n')
48+
print(f"Created sample file: {file_path}")
49+
return True
50+
except Exception as e:
51+
print(f"Error creating sample file: {e}")
52+
return False
53+
54+
55+
def main():
56+
"""Main function to run the random file content picker."""
57+
print("Random File Content Picker")
58+
print("=" * 40)
59+
60+
# Check if file path is provided as command line argument
61+
if len(sys.argv) > 1:
62+
file_path = sys.argv[1]
63+
else:
64+
# Interactive mode
65+
file_path = input("Enter file path (or press Enter for sample quotes): ").strip()
66+
67+
# Use default sample file if no path provided
68+
if not file_path:
69+
file_path = "sample_quotes.txt"
70+
71+
# Create sample file if it doesn't exist
72+
if not os.path.exists(file_path):
73+
print("\nNo file specified. Creating sample quotes file...")
74+
if not create_sample_file(file_path):
75+
return
76+
77+
# Check if file exists
78+
if not os.path.exists(file_path):
79+
print(f"\nError: File does not exist: {file_path}")
80+
81+
# Offer to create sample file
82+
if input("Create a sample quotes file? (y/n): ").lower().startswith('y'):
83+
file_path = "sample_quotes.txt"
84+
if not create_sample_file(file_path):
85+
return
86+
else:
87+
return
88+
89+
# Get and display random line
90+
print(f"\nReading from: {file_path}")
91+
random_line = get_random_line(file_path)
92+
93+
if random_line:
94+
print("\n" + "=" * 50)
95+
print("Random Pick:")
96+
print(f" {random_line}")
97+
print("=" * 50)
98+
99+
# Show file stats
100+
try:
101+
with open(file_path, 'r', encoding='utf-8') as file:
102+
total_lines = len([line for line in file if line.strip()])
103+
print(f"\nFile contains {total_lines} lines")
104+
except:
105+
pass
106+
107+
108+
if __name__ == "__main__":
109+
main()

0 commit comments

Comments
 (0)