Curso de Python 3 do Básico ao Avançado

Overview

Curso de Python 3 do Básico ao Avançado

Desafio: Buscador de arquivos

Criar um programa que faça a pesquisa de arquivos. É fornecido o caminho e um termo de pesquisa.

O programa ira pesquisar no caminho fornecido, entrando nas pastas e subpastas procurando pelo termo fornecido pelo usuário. O programa irá retornar as informações:

  • Diretório do arquivo
  • Nome
  • Extensão
  • Tamanho

Solução:

from buscadearquivos import pesquisar

caminho = input('Digite o caminho onde o arquivo possa estar: ')
termo = input('Digite o termo da pesquisa: ')

pesquisar(caminho, termo)

Conforme o codigo abaixo, foi ultilizado a biblioteca "os" para realizar as pesquisas dos arquivos.
Para fornecer o tamanho na medida correta foi criado a função formata_tamanho, que compara o tamanho fornecido pelo programa, divide caso necessário e retorna o nome de medida correta.

import os

def pesquisar(caminho_procura, termo_procura):

    def formata_tamanho(tamanho):
        base = 1024
        kilo = base
        mega = base ** 2
        giga = base ** 3
        tera = base ** 4
        peta = base ** 5

        if tamanho < kilo:
            texto = 'B'
        elif tamanho < mega:
            tamanho /= kilo
            texto = 'K'
        elif tamanho < giga:
            tamanho /= mega
            texto = 'M'
        elif tamanho < tera:
            tamanho /= giga
            texto = 'G'
        elif tamanho < peta:
            tamanho /= tera
            texto = 'T'
        else:
            tamanho /= peta
            texto = 'P'

        tamanho = round(tamanho, 2)
        return f'{tamanho}{texto}'.replace('.',',')


    contador = 0
    for raiz, diretorios, arquivos in os.walk(caminho_procura):
        for arquivo in arquivos:
            if termo_procura in arquivo:
                try:
                    contador += 1
                    caminho_completo = os.path.join(raiz, arquivo)
                    nome_arquivo, ext_arquivo = os.path.splitext(arquivo)
                    tamanho = os.path.getsize(caminho_completo)
                    print()
                    print('Encontrei o arquivo: ', arquivo)
                    print('Caminho:', caminho_completo)
                    print('Nome:', nome_arquivo)
                    print('Extensão: ', ext_arquivo)
                    print('Tamanho: ', formata_tamanho(tamanho))
                except PermissionError as e:
                    print('Sem permissões de acesso!')
                except FileNotFoundError as e:
                    print('Arquivo não encontrado!')
                except Exception as e:
                    print('Erro desconhecido!')

    print()
    print(f'{contador} arquivo(s) encontrado(s).')

Terminal:

Conforme a imagem abaixo, ao final da pesquisa o programa mostra quantos arquivos foram econtrados com o termo inserido.

exemplo no terminal como o programa se comporta

Owner
Diego Guedes
Diego Guedes
Capture screen and download off Roku based devices

rokuview Capture screen and download off Roku based devices Tested on Hisense TV with Roku OS built-in No guarantee this will work with all Roku model

3 May 27, 2021
Programa que organiza pastas automaticamente

📂 Folder Organizer 📂 Programa que organiza pastas automaticamente Requisitos • Como usar • Melhorias futuras • Capturas de Tela Requisitos Antes de

João Victor Vilela dos Santos 1 Nov 02, 2021
This is the key combo trainer for League of Legends and Dota 2 players.

This is the key combo trainer for League of Legends and Dota 2 players. Place the mouse cursor on the blue point and press the key combo from the upper-left side of the screen.

Ilya Shpigor 1 Jan 31, 2022
Быстрый локальный старт

Быстрый локальный старт

Anton Ogorodnikov 1 Sep 28, 2021
This program generates automatically new folders containing old version of program

Automated Folder Versions Generator by Sergiy Grimoldi - V.0.0.2 This program generates automatically new folders containing old version of something

Sergiy Grimoldi 1 Dec 23, 2021
Coffeematcher is a python library to randomly match participants for coffee meetings.

coffeematcher coffeematcher is a python library to randomly match participants for coffee meetings. Installation Clone the repository: git clone https

Thomas Wesselink 3 May 06, 2022
This module is for finding the execution time of a whole python program

exetime 3.8 This module is for finding the execution time of a whole program How to install $ pip install exetime Contents: General Information Instru

Saikat Das 4 Oct 18, 2021
Petuhlang is a joke-like language, based on Python.

Petuhlang is a joke-like language, based on Python. It updates builtins to make a new syntax based on operators rewrite.

DenyS 9 Jun 19, 2022
token vesting escrow with cliff and clawback

Yearn Vesting Escrow A modified version of Curve Vesting Escrow contracts with added functionality: An escrow can have a start_date in the past.

62 Dec 08, 2022
A simple and convenient build-and-run system for C and C++.

smake Smake is a simple and convenient build-and-run system for C and C++ projects. Why make another build system? CMake and GNU Make are great build

Venkataram Edavamadathil Sivaram 18 Nov 13, 2022
A project to find out all the words in a crossword.

A project to find out all the words in a crossword.

Kalpesh Dhoundiyal 1 Feb 06, 2022
NeoInterface - Neo4j made easy for Python programmers!

Neointerface - Neo4j made easy for Python programmers! A Python interface to use the Neo4j graph database, and simplify its use. class NeoInterface: C

15 Dec 15, 2022
Convert temps in your Alfred search bar

Alfred Temp Converter Convert temps in your Alfred search bar. Download Here Usage: temp 100f converts to Celsius, Kelvin, and Rankine. temp 100c conv

Justin Hamilton 4 Apr 11, 2022
Snakemake worflow to process and filter long read data from Oxford Nanopore Technologies.

Nanopore-Workflow Snakemake workflow to process and filter long read data from Oxford Nanopore Technologies. It is designed to compare whole human gen

5 May 13, 2022
Cisco IOS-XE Operations Program. Shows operational data using restconf and yang

XE-Ops View operational and config data from devices running Cisco IOS-XE software. NoteS The build folder is the latest build. All other files are fo

18 Jul 23, 2022
Ultimate Score Server for RealistikOsu

USSR Ultimate Score Server for RealistikOsu (well not just us but it makes the acronym work.) Also I wonder how long this name will last. What is this

RealistikOsu! 15 Dec 14, 2022
run-js Goal: The Easiest Way to Run JavaScript in Python

run-js Goal: The Easiest Way to Run JavaScript in Python features Stateless Async JS Functions No Intermediary Files Functional Programming CommonJS a

Daniel J. Dufour 9 Aug 16, 2022
A simple armature retargeting tool for Blender

Simple-Retarget-Tool-Blender A simple armature retargeting tool for Blender Update V2: Set Rest Pose to easily apply rest pose. Preset Import/Export.

Fahad Hasan Pathik 74 Jan 04, 2023
Use Ghidra Structs in Python

Strudra Welcome to Strudra, a way to craft Ghidra structs in python, using ghidra_bridge. Example First, init Strudra - you can pass in a custom Ghidr

Dominik Maier 27 Nov 24, 2022
Zeus - Advanced Punishments with Embeds.

Zeus Advanced Punishments with Embeds. Make sure to put the Discord Bot Token in the " TOKEN = '' " Language Python Features Ban Kick Mute Unmute Warn

2 Jan 05, 2022