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
Virtual webcam that takes real webcam footage and replaces the background in order to have Virtual Backgrounds in MS Teams for Linux where the feature is unimplemented.

Background Remover The Need It's been good long while since Microsoft first released a Teams version for Linux and yet, one of Teams' coolest features

Dylan Turner 80 Dec 20, 2022
Repo created for the purpose of adding any kind of programs and projects

Programs and Project Repository A repository for adding programs and projects of any kind starting from beginners level to expert ones Contributing to

Unicorn Dev Community 3 Nov 02, 2022
Exactly what it sounds like, which is something rad

EyeWitnessTheFitness External recon got ya down? That scan prevention system preventing you from enumerating web pages? Well look no further, I have t

Ellis Springe 18 Dec 31, 2022
Python screenshot library, replacement for the Pillow ImageGrab module on Linux.

tldr: Use Pillow The pyscreenshot module is obsolete in most cases. It was created because PIL ImageGrab module worked on Windows only, but now Linux

455 Dec 24, 2022
Project Interface For nextcord-ext

Project Interface For nextcord-ext

nextcord-ext 1 Nov 13, 2021
用于红队成员初步快速攻击的全自动化工具。

关于 Author:m0sway Mail:[email protected] Github:https://www.github.com/m0sway/Jud JuD是

m0sway 46 Jul 21, 2022
A Klipper plugin for accurate Z homing

Stable Z Homing for Klipper A Klipper plugin for accurate Z homing This plugin provides a new G-code command, STABLE_Z_HOME, which homes Z repeatedly

Matthew Lloyd 24 Dec 28, 2022
Curso de Python 3 do Básico ao Avançado

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 te

Diego Guedes 1 Jan 21, 2022
Automate your Microsoft Learn Student Ambassadors event certificate with Python

Microsoft Learn Student Ambassador Certificate Automation This repo simply use a template certificate docx file and generates certificates both docx a

Muhammed Oğuz 24 Aug 24, 2022
Laurence Billingham 1 Feb 16, 2022
Custom component to calculate estimated power consumption of lights and other appliances

Custom component to calculate estimated power consumption of lights and other appliances. Provides easy configuration to get virtual power consumption sensors in Home Assistant for all your devices w

Bram Gerritsen 552 Dec 28, 2022
Thinky nature dots with python

Thinky Nature Welcome to my rice dotfiles of my ThinkPad X230 You surely will need to change some configs to fit your files and stuff and maybe tweak

Daniel Mironow 26 Dec 02, 2022
solsim is the Solana complex systems simulator. It simulates behavior of dynamical systems—DeFi protocols, DAO governance, cryptocurrencies, and more—built on the Solana blockchain

solsim is the Solana complex systems simulator. It simulates behavior of dynamical systems—DeFi protocols, DAO governance, cryptocurrencies, and more—built on the Solana blockchain

William Wolf 12 Jul 13, 2022
Small C-like language compiler for the Uxn assembly language

Pyuxncle is a single-pass compiler for a small subset of C (albeit without the std library). This compiler targets Uxntal, the assembly language of the Uxn virtual computer. The output Uxntal is not

CPunch 13 Jun 28, 2022
A bunch of codes for procedurally modeling and texturing futuristic cities.

Procedural Futuristic City This is our final project for CPSC 479. We created a procedural futuristic city complete with Worley noise procedural textu

1 Dec 22, 2021
A hackerank problems, solution repository

This is a repository for all hackerank challenges kindly note this is for learning purposes and if you wish to contribute, dont hesitate all submision

Tyler Mwalo Kenneth's 1 Dec 20, 2021
Spooky Castle Project

Spooky Castle Project Here is a repository where I have placed a few workflow scripts that could be used to automate the blender to godot sprite pipel

3 Jan 17, 2022
A simple and usefull python calculator.

simplepy-calculator Your simple and fresh calculator. Getting Started Install python3 from the oficial python website or via terminal. Clone this repo

Felix Sanchez 1 Jan 18, 2022
It converts ING BANK account historic into a csv file you can import in HomeBank application.

ing2homebank It converts your ING Bank account historic csv file into another csv file you can import in HomeBank application

1 Feb 14, 2022
Esercizi di Python svolti per il biennio di Tecnologie Informatiche.

Esercizi di Python Un piccolo aiuto per Sofia che nel 2° quadrimestre inizierà Python :) Questo repository (termine tecnico di Git) puoi trovare tutti

Leonardo Essam Dei Rossi 2 Nov 07, 2022