Pyhton move files according to quantity

Asked

Viewed 48 times

-3

I’m trying to create a script that:

  • Move from a source folder to a destination folder 9 files that start with '_A_'.

Obs: Inside the source folder there will be dozens of files starting with '_A_', but I wish only 9 to be moved.

Code

import shutil
import os

pasta_origem = r'D:\Pasta_Origem'    # pasta de origem
pasta_destino = r'D:\Pasta_Destino'  # pasta de destino
files = os.listdir(pasta_origem)     # lista os arquivos dentro da pasta
os.chdir(pasta_origem)               # vai para o diretorio de destino

# este loop é para selecionar apenas 9 arquivos que comecem com '_A_'.
# dentro desta pasta haverao dezenas de arquivos comecando com '_A_', quero que ele pegue so 9.

for file in files:
   if file.startswith('_A_') and files.count(9):
       print(file)  # apenas para visualizar os arquivos que serao movidos
       shutil.move(file, pasta_destino)

1 answer

3

files.count(9) counts how many times the int 9 appears in the list files. As he does not appear any time (files is a list of strings), returns 0. A conditional in form

if alguma_expressao and 0 

will always be false, since bool(0) amounts to False. Soon, the lines below conditional as you wrote are never executed.

Use a simple counter to run something N times, for example:

files_to_move = 9
for file in files:
    if file.startswith('_A_'):
        print(file)  # apenas para visualizar os arquivos que serao movidos
        shutil.move(file, pasta_destino)
        files_to_move -= 1
    if files_to_move == 0:  # sair do loop
        break
  • Dude, perfect!!!! was exactly what I wanted. before I asked the question, I’ve been trying to do it for over a week. Thank you so much!

  • I’m happy to help :)

Browser other questions tagged

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