Rename folders by changing lowercase characters to uppercase and get the total number of folders changed

Asked

Viewed 101 times

2

I’m creating a python script to rename folder names that are lowercase to uppercase. In the code example below I already get this task.

import os
basedir = '/content/drive/My Drive/Colab Notebooks/Teste'

for name_folder in os.listdir(basedir):
    os.rename(os.path.join(basedir, name_folder), 
              os.path.join(basedir, name_folder.upper()))

I would like more information about the base directory files (base)

Questions:

1. Total number of files.

2. Total number of folders.

3. Total number of pulp processed.

  • I guess you forgot to rename the basedir for diretorio_base there on the second line.

  • 1

    Thanks for the remark. I already edited the question.

  • 1

    @Rfroes87, your answer was exactly what I wanted. Thanks.

  • @Rfroes87, I’m changing the code a little bit, is there an easy way to implement a review if the path is really a directory? dir = str(input('Digite um caminho: '))

  • You can use the function os.path.isdir.

1 answer

2


I believe the function walk would be more appropriate for your use case. You could use it this way:

import os

# Inicializando estatísticas
num_files, num_dir, num_transform = [0] * 3

"""
Aqui cada diretório e subdiretório vai ser uma tupla com 3 elementos contendo
respectivamente o nome do diretório e o total de subdiretórios e arquivos contidos
no mesmo
"""
for dir, subdirs, files in os.walk('/content/drive/My Drive/Colab Notebooks/Teste'):
   # Iterando subdiretórios
   for subdir in subdirs:

      # Caso o subdiretório não esteja em caixa alta
      if not subdir.isupper():

         # Renomear diretório da mesma forma e incrementar contador de 'transformação'
         os.rename(os.path.join(dir, subdir), os.path.join(dir, subdir.upper()))
         num_transform += 1

      # Incrementar total de diretórios lidos
      num_dir += 1

   # Contar número de arquivos no diretório correntes adicionando ao contador apropriado
   num_files += len(files)

Output example

>>> print(f'num_dir: {num_dir} / num_files: {num_files} / num_transform: {num_transform}')
num_dir: 3 / num_files: 2 / num_transform: 2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.