-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_reader.py
More file actions
95 lines (71 loc) · 2.58 KB
/
file_reader.py
File metadata and controls
95 lines (71 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import os
try:
# Try to import tkinter for GUI file picker
import tkinter as tk
from tkinter import filedialog
TK_AVAILABLE = True
except ImportError:
TK_AVAILABLE = False
def clear_screen():
"""Clear the screen (works on Windows, Mac, Linux)."""
os.system('cls' if os.name == 'nt' else 'clear')
def read_file_from_path():
"""Read a file using a path the user types."""
file_path = input("\nEnter the file name or full path: ").strip()
if not os.path.isfile(file_path):
print(f"\n❌ Error: File '{file_path}' not found.")
return
print(f"\n✔️ Reading: {file_path}\n")
try:
with open(file_path, "r", encoding="utf-8") as file:
content = file.read()
if content.strip() == "":
print("⚠️ The file is empty.")
else:
print(content)
except Exception as e:
print(f"\n⚠️ Unexpected error: {e}")
def read_file_with_gui():
"""Use a GUI dialog to pick a file (if tkinter is available)."""
if not TK_AVAILABLE:
print("\n⚠️ GUI not available (tkinter is not installed).")
return
print("\n📂 Opening file chooser window...")
# Set up a hidden Tkinter root window
root = tk.Tk()
root.withdraw() # Hide the main window
file_path = filedialog.askopenfilename(title="Select a file to open")
if not file_path:
print("❌ No file selected.")
return
print(f"\n✔️ Reading: {file_path}\n")
try:
with open(file_path, "r", encoding="utf-8") as file:
content = file.read()
if content.strip() == "":
print("⚠️ The file is empty.")
else:
print(content)
except Exception as e:
print(f"\n⚠️ Unexpected error: {e}")
def main_menu():
while True:
clear_screen()
print("📄 Simple File Reader")
print("----------------------")
print("1) Read file by typing path")
print("2) Read file using file picker (GUI)")
print("3) Exit")
choice = input("\nChoose an option (1-3): ").strip()
if choice == "1":
read_file_from_path()
elif choice == "2":
read_file_with_gui()
elif choice == "3":
print("\n👋 Goodbye!")
break
else:
print("\n❌ Invalid choice. Please enter 1, 2, or 3.")
input("\nPress Enter to continue...")
if __name__ == "__main__":
main_menu()