0% found this document useful (0 votes)
19 views

file exp code

Blah

Uploaded by

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

file exp code

Blah

Uploaded by

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

import os

import tkinter as tk
from tkinter import filedialog, messagebox, ttk
from datetime import datetime
import shutil

class FileExplorer:
def __init__(self, root):
self.root = root
self.root.title("Advanced File Explorer")
self.root.geometry("1000x700")

# Status bar
self.status_var = tk.StringVar()
self.status_var.set("Welcome to Advanced File Explorer")
self.status_bar = tk.Label(self.root, textvariable=self.status_var, relief=tk.SUNKEN,
anchor="w")
self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)

# Current directory label


self.current_dir_label = tk.Label(self.root, text="Current Directory:", anchor='w')
self.current_dir_label.pack(fill=tk.X, padx=10, pady=5)

self.current_dir_var = tk.StringVar()
self.current_dir_var.set(os.getcwd())
self.current_dir_entry = tk.Entry(self.root, textvariable=self.current_dir_var,
state='readonly')
self.current_dir_entry.pack(fill=tk.X, padx=10, pady=5)

# Search bar
self.search_frame = tk.Frame(self.root)
self.search_frame.pack(fill=tk.X, padx=10, pady=5)

self.search_var = tk.StringVar()
self.search_entry = tk.Entry(self.search_frame, textvariable=self.search_var, width=50)
self.search_entry.pack(side=tk.LEFT, padx=5)

self.search_button = tk.Button(self.search_frame, text="Search",


command=self.search_files)
self.search_button.pack(side=tk.LEFT, padx=5)
# File tree view
self.tree = ttk.Treeview(self.root, columns=("Type", "Size", "Modified"),
show="headings")
self.tree.heading("Type", text="Type")
self.tree.heading("Size", text="Size")
self.tree.heading("Modified", text="Last Modified")
self.tree.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)

self.tree.bind("<Double-1>", self.on_item_double_click)
self.tree.bind("<Button-3>", self.show_context_menu)

# Context menu
self.context_menu = tk.Menu(self.root, tearoff=0)
self.context_menu.add_command(label="Open", command=self.open_selected_item)
self.context_menu.add_command(label="Delete",
command=self.delete_selected_item)
self.context_menu.add_command(label="Rename",
command=self.rename_selected_item)
self.context_menu.add_command(label="Move", command=self.move_selected_item)
self.context_menu.add_command(label="Copy", command=self.copy_selected_item)
self.context_menu.add_command(label="Properties", command=self.view_properties)

# Buttons
self.button_frame = tk.Frame(self.root)
self.button_frame.pack(fill=tk.X, padx=10, pady=5)

self.open_button = tk.Button(self.button_frame, text="Open Directory",


command=self.open_directory)
self.open_button.pack(side=tk.LEFT, padx=5)

self.refresh_button = tk.Button(self.button_frame, text="Refresh",


command=self.refresh)
self.refresh_button.pack(side=tk.LEFT, padx=5)

self.sort_button = tk.Button(self.button_frame, text="Sort", command=self.sort_files)


self.sort_button.pack(side=tk.LEFT, padx=5)

self.exit_button = tk.Button(self.button_frame, text="Exit", command=self.root.quit)


self.exit_button.pack(side=tk.RIGHT, padx=5)

# Keyboard shortcuts
self.root.bind("<Control-o>", lambda e: self.open_directory())
self.root.bind("<Control-r>", lambda e: self.refresh())
self.root.bind("<Control-q>", lambda e: self.root.quit())

# Initialize the file view


self.populate_tree(os.getcwd())

def update_status(self, message):


self.status_var.set(message)

def open_directory(self):
directory = filedialog.askdirectory()
if directory:
self.current_dir_var.set(directory)
self.populate_tree(directory)
self.update_status(f"Opened directory: {directory}")

def refresh(self):
self.populate_tree(self.current_dir_var.get())
self.update_status("Refreshed directory view")

def populate_tree(self, directory):


for item in self.tree.get_children():
self.tree.delete(item)

try:
for entry in os.scandir(directory):
entry_type = "File" if entry.is_file() else "Directory"
entry_size = os.path.getsize(entry) if entry.is_file() else ""
last_modified = datetime.fromtimestamp(entry.stat().st_mtime).strftime('%Y-%m-
%d %H:%M:%S')

self.tree.insert("", "end", iid=entry.path, text=entry.name,


values=(entry_type, entry_size, last_modified))
self.update_status(f"Loaded contents of: {directory}")
except Exception as e:
messagebox.showerror("Error", f"Failed to open directory: {str(e)}")
self.update_status("Error loading directory")

def on_item_double_click(self, event):


self.open_selected_item()
def open_selected_item(self):
selected_item = self.tree.selection()
if selected_item:
item_path = selected_item[0]
if os.path.isdir(item_path):
self.current_dir_var.set(item_path)
self.populate_tree(item_path)
self.update_status(f"Opened folder: {item_path}")
elif os.path.isfile(item_path):
self.open_file(item_path)

def open_file(self, file_path):


try:
with open(file_path, "r") as file:
content = file.read()

file_viewer = tk.Toplevel(self.root)
file_viewer.title(os.path.basename(file_path))
text_widget = tk.Text(file_viewer, wrap="word")
text_widget.insert("1.0", content)
text_widget.pack(fill=tk.BOTH, expand=True)
self.update_status(f"Opened file: {file_path}")

except Exception as e:
messagebox.showerror("Error", f"Failed to open file: {str(e)}")
self.update_status("Error opening file")

def delete_selected_item(self):
selected_item = self.tree.selection()
if selected_item:
item_path = selected_item[0]
try:
if os.path.isdir(item_path):
os.rmdir(item_path)
else:
os.remove(item_path)
self.populate_tree(self.current_dir_var.get())
self.update_status(f"Deleted: {item_path}")
except Exception as e:
messagebox.showerror("Error", f"Failed to delete item: {str(e)}")
self.update_status("Error deleting item")

def rename_selected_item(self):
selected_item = self.tree.selection()
if selected_item:
item_path = selected_item[0]
new_name = filedialog.asksaveasfilename(initialdir=os.path.dirname(item_path),
initialfile=os.path.basename(item_path))
if new_name:
try:
os.rename(item_path, new_name)
self.populate_tree(self.current_dir_var.get())
self.update_status(f"Renamed to: {new_name}")
except Exception as e:
messagebox.showerror("Error", f"Failed to rename item: {str(e)}")
self.update_status("Error renaming item")

def move_selected_item(self):
selected_item = self.tree.selection()
if selected_item:
item_path = selected_item[0]
target_directory = filedialog.askdirectory()
if target_directory:
try:
shutil.move(item_path, target_directory)
self.populate_tree(self.current_dir_var.get())
self.update_status(f"Moved to: {target_directory}")
except Exception as e:
messagebox.showerror("Error", f"Failed to move item: {str(e)}")
self.update_status("Error moving item")

def copy_selected_item(self):
selected_item = self.tree.selection()
if selected_item:
item_path = selected_item[0]
target_directory = filedialog.askdirectory()
if target_directory:
try:
if os.path.isdir(item_path):
shutil.copytree(item_path, os.path.join(target_directory,
os.path.basename(item_path)))
else:
shutil.copy2(item_path, target_directory)
self.populate_tree(self.current_dir_var.get())
self.update_status(f"Copied to: {target_directory}")
except Exception as e:
messagebox.showerror("Error", f"Failed to copy item: {str(e)}")
self.update_status("Error copying item")

def search_files(self):
query = self.search_var.get().lower()
if query:
for item in self.tree.get_children():
self.tree.delete(item)

directory = self.current_dir_var.get()
try:
for root, _, files in os.walk(directory):
for file in files:
if query in file.lower():
file_path = os.path.join(root, file)
entry_size = os.path.getsize(file_path)
last_modified =
datetime.fromtimestamp(os.path.getmtime(file_path)).strftime('%Y-%m-%d %H:%M:%S')

self.tree.insert("", "end", iid=file_path, text=file,


values=("File", entry_size, last_modified))
self.update_status(f"Search completed for: {query}")
except Exception as e:
messagebox.showerror("Error", f"Search failed: {str(e)}")
self.update_status("Error during search")

def show_context_menu(self, event):


try:
selected_item = self.tree.selection()
if selected_item:
self.context_menu.post(event.x_root, event.y_root)
except Exception as e:
messagebox.showerror("Error", f"Failed to show context menu: {str(e)}")
self.update_status("Error showing context menu")

def sort_files(self):
# Sort files in ascending order by name
try:
directory = self.current_dir_var.get()
files = sorted(os.scandir(directory), key=lambda x: x.name.lower())
for item in self.tree.get_children():
self.tree.delete(item)

for entry in files:


entry_type = "File" if entry.is_file() else "Directory"
entry_size = os.path.getsize(entry) if entry.is_file() else ""
last_modified = datetime.fromtimestamp(entry.stat().st_mtime).strftime('%Y-%m-
%d %H:%M:%S')

self.tree.insert("", "end", iid=entry.path, text=entry.name,


values=(entry_type, entry_size, last_modified))
self.update_status("Files sorted by name")
except Exception as e:
messagebox.showerror("Error", f"Failed to sort files: {str(e)}")
self.update_status("Error sorting files")

def view_properties(self):
# Show properties of the selected item
selected_item = self.tree.selection()
if selected_item:
item_path = selected_item[0]
try:
is_directory = os.path.isdir(item_path)
size = self.get_human_readable_size(os.path.getsize(item_path)) if not is_directory
else "N/A"
last_modified =
datetime.fromtimestamp(os.path.getmtime(item_path)).strftime('%Y-%m-%d %H:%M:%S')
properties_message = (
f"Name: {os.path.basename(item_path)}\n"
f"Type: {'Directory' if is_directory else 'File'}\n"
f"Size: {size}\n"
f"Last Modified: {last_modified}"
)
messagebox.showinfo("Properties", properties_message)
self.update_status(f"Viewed properties for: {item_path}")
except Exception as e:
messagebox.showerror("Error", f"Failed to view properties: {str(e)}")
self.update_status("Error viewing properties")

@staticmethod
def get_human_readable_size(size):
# Convert bytes to human-readable size
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size < 1024:
return f"{size:.2f} {unit}"
size /= 1024
return f"{size:.2f} PB"

if __name__ == "__main__":
root = tk.Tk()
app = FileExplorer(root)
root.mainloop()

You might also like