Agora que você entende como trabalhar com caminhos de arquivos em Python, vamos colocar esse conhecimento em prática criando um gerenciador de arquivos cross-platform simples. Este aplicativo demonstrará como executar operações de arquivo comuns, garantindo a compatibilidade em diferentes sistemas operacionais.
Configurando a Estrutura do Projeto
Primeiro, vamos criar uma estrutura de projeto adequada:
- Crie um novo diretório chamado
file_manager:
mkdir -p /home/labex/project/file_manager
- Dentro deste diretório, crie um novo arquivo chamado
app.py:
touch /home/labex/project/file_manager/app.py
- Abra o arquivo
app.py no editor e adicione o seguinte código:
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!")
- Salve o arquivo.
Executando o Aplicativo Gerenciador de Arquivos
Agora, vamos executar nosso aplicativo gerenciador de arquivos:
cd /home/labex/project
python3 file_manager/app.py
Você deve ver a saída mostrando várias operações de arquivo:
- Criando arquivos e diretórios
- Listando o conteúdo do diretório
- Movendo arquivos
- Excluindo arquivos
Este aplicativo demonstra vários conceitos importantes para trabalhar com arquivos em diferentes plataformas:
- Usando
os.path.join() para criar caminhos de arquivo
- Convertendo entre caminhos relativos e absolutos
- Trabalhando com arquivos e diretórios
- Movendo e excluindo arquivos
- Tratando erros durante operações de arquivo
Estendendo o Aplicativo
Vamos criar mais um script para demonstrar como copiar arquivos entre diretórios:
- Crie um novo arquivo chamado
file_operations.py no diretório do projeto:
touch /home/labex/project/file_operations.py
- Adicione o seguinte código:
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!")
- Salve o arquivo.
- Execute o script:
python3 file_operations.py
Este script demonstra:
- Obtendo informações do sistema (tipo de SO, separador de caminho)
- Criando estruturas de diretório recursivamente
- Copiando arquivos entre diretórios
- Lidando com caminhos aninhados que podem não existir
A combinação desses scripts mostra como você pode trabalhar com arquivos e diretórios de uma forma que funcione corretamente em diferentes sistemas operacionais, o que é essencial para escrever aplicativos Python portáveis.