Создание кроссплатформенного файлового менеджера
Теперь, когда вы знаете, как работать с путями к файлам в Python, давайте применить эти знания на практике, создав простой кроссплатформенный файловый менеджер. Это приложение продемонстрирует, как выполнять общие файловые операции, обеспечивая при этом совместимость на разных операционных системах.
Настройка структуры проекта
Сначала создадим правильную структуру проекта:
- Создайте новую директорию с именем
file_manager:
mkdir -p /home/labex/project/file_manager
- Внутри этой директории создайте новый файл с именем
app.py:
touch /home/labex/project/file_manager/app.py
- Откройте файл
app.py в редакторе и добавьте следующий код:
import os
import shutil
from datetime import datetime
class FileManager:
def __init__(self, root_dir=None):
"""Initialize the file manager with a root directory."""
if root_dir is None:
self.root_dir = os.getcwd()
else:
self.root_dir = os.path.abspath(root_dir)
## Create a storage directory if it doesn't exist
self.storage_dir = os.path.join(self.root_dir, "storage")
if not os.path.exists(self.storage_dir):
os.makedirs(self.storage_dir)
print(f"Created storage directory: {self.storage_dir}")
def list_directory(self, directory=None):
"""List the contents of the specified directory."""
if directory is None:
directory = self.storage_dir
else:
## Convert relative path to absolute
if not os.path.isabs(directory):
directory = os.path.join(self.storage_dir, directory)
if not os.path.exists(directory):
print(f"Directory does not exist: {directory}")
return
if not os.path.isdir(directory):
print(f"Not a directory: {directory}")
return
print(f"\nContents of {directory}:")
items = os.listdir(directory)
if not items:
print(" (empty directory)")
return
for item in items:
item_path = os.path.join(directory, item)
item_stat = os.stat(item_path)
mod_time = datetime.fromtimestamp(item_stat.st_mtime).strftime('%Y-%m-%d %H:%M:%S')
if os.path.isdir(item_path):
print(f" 📁 {item} - Modified: {mod_time}")
else:
size = item_stat.st_size
if size < 1024:
size_str = f"{size} bytes"
elif size < 1024 * 1024:
size_str = f"{size/1024:.1f} KB"
else:
size_str = f"{size/(1024*1024):.1f} MB"
print(f" 🗒️ {item} - Size: {size_str} - Modified: {mod_time}")
def create_file(self, filename, content=""):
"""Create a new file with the given content."""
file_path = os.path.join(self.storage_dir, filename)
try:
with open(file_path, 'w') as f:
f.write(content)
print(f"Created file: {file_path}")
except Exception as e:
print(f"Error creating file: {e}")
def create_directory(self, dirname):
"""Create a new directory."""
dir_path = os.path.join(self.storage_dir, dirname)
try:
os.makedirs(dir_path, exist_ok=True)
print(f"Created directory: {dir_path}")
except Exception as e:
print(f"Error creating directory: {e}")
def delete_item(self, item_name):
"""Delete a file or directory."""
item_path = os.path.join(self.storage_dir, item_name)
if not os.path.exists(item_path):
print(f"Item does not exist: {item_path}")
return
try:
if os.path.isdir(item_path):
shutil.rmtree(item_path)
print(f"Deleted directory: {item_path}")
else:
os.remove(item_path)
print(f"Deleted file: {item_path}")
except Exception as e:
print(f"Error deleting item: {e}")
def move_item(self, source, destination):
"""Move a file or directory from source to destination."""
source_path = os.path.join(self.storage_dir, source)
dest_path = os.path.join(self.storage_dir, destination)
if not os.path.exists(source_path):
print(f"Source does not exist: {source_path}")
return
try:
shutil.move(source_path, dest_path)
print(f"Moved {source_path} to {dest_path}")
except Exception as e:
print(f"Error moving item: {e}")
## Main program to demonstrate the file manager
if __name__ == "__main__":
print("Cross-Platform File Manager")
print("===========================")
manager = FileManager()
## Create some test files and directories
manager.create_file("hello.txt", "Hello, world! This is a test file.")
manager.create_file("data.csv", "id,name,age\n1,Alice,28\n2,Bob,32")
manager.create_directory("documents")
manager.create_file("documents/notes.txt", "These are some notes in the documents folder.")
## List contents
manager.list_directory()
## Move a file
manager.move_item("hello.txt", "documents/hello.txt")
## List contents after move
print("\nAfter moving hello.txt to documents folder:")
manager.list_directory()
manager.list_directory("documents")
## Delete a file
print("\nDeleting data.csv file:")
manager.delete_item("data.csv")
manager.list_directory()
print("\nFile operations completed successfully!")
- Сохраните файл.
Запуск файлового менеджера
Теперь запустим наше файловое менеджерское приложение:
cd /home/labex/project
python3 file_manager/app.py
Вы должны увидеть вывод, показывающий различные файловые операции:
- Создание файлов и директорий
- Вывод содержимого директории
- Перемещение файлов
- Удаление файлов
Это приложение демонстрирует несколько важных концепций работы с файлами на разных платформах:
- Использование
os.path.join() для создания путей к файлам
- Преобразование между относительными и абсолютными путями
- Работа с файлами и директориями
- Перемещение и удаление файлов
- Обработка ошибок при выполнении файловых операций
Расширение приложения
Создадим еще один скрипт, чтобы показать, как копировать файлы между директориями:
- Создайте новый файл с именем
file_operations.py в директории проекта:
touch /home/labex/project/file_operations.py
- Добавьте следующий код:
import os
import shutil
import platform
def print_system_info():
"""Print information about the current operating system."""
print(f"Operating System: {platform.system()}")
print(f"OS Version: {platform.version()}")
print(f"Python Version: {platform.python_version()}")
print(f"Path Separator: {os.path.sep}")
print(f"Current Directory: {os.getcwd()}")
def copy_file(source, destination):
"""Copy a file from source to destination."""
try:
## Ensure the destination directory exists
dest_dir = os.path.dirname(destination)
if dest_dir and not os.path.exists(dest_dir):
os.makedirs(dest_dir)
print(f"Created directory: {dest_dir}")
## Copy the file
shutil.copy2(source, destination)
print(f"Copied: {source} → {destination}")
## Get file info
file_size = os.path.getsize(destination)
print(f"File size: {file_size} bytes")
return True
except Exception as e:
print(f"Error copying file: {e}")
return False
## Main program
if __name__ == "__main__":
print("Cross-Platform File Operations")
print("==============================")
print_system_info()
## Create a test directory structure
base_dir = os.path.join(os.getcwd(), "test_copy")
if not os.path.exists(base_dir):
os.makedirs(base_dir)
source_dir = os.path.join(base_dir, "source")
dest_dir = os.path.join(base_dir, "destination")
if not os.path.exists(source_dir):
os.makedirs(source_dir)
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
## Create a test file
test_file = os.path.join(source_dir, "test.txt")
with open(test_file, 'w') as f:
f.write("This is a test file for copying operations.\n" * 10)
print(f"\nCreated test file: {test_file}")
## Copy the file to the destination
dest_file = os.path.join(dest_dir, "test_copy.txt")
copy_file(test_file, dest_file)
## Try copying to a nested directory that doesn't exist yet
nested_dest = os.path.join(dest_dir, "nested", "folders", "test_nested.txt")
copy_file(test_file, nested_dest)
print("\nFile operations completed!")
- Сохраните файл.
- Запустите скрипт:
python3 file_operations.py
Этот скрипт демонстрирует:
- Получение информации о системе (тип операционной системы, разделитель пути)
- Рекурсивное создание структур директорий
- Копирование файлов между директориями
- Обработку вложенных путей, которые могут не существовать
Совокупность этих скриптов показывает, как можно работать с файлами и директориями таким образом, чтобы это работало правильно на разных операционных системах, что является важным условием для написания переносимых приложений на Python.