Python - Moving files to another folder

Asked

Viewed 6,485 times

1

Could someone give me a help in the code below?

Goal: move files from one folder to another.

I have on the desktop two folders, one called "test" and the other "teste2".

At first, I have 7 text files extension ". txt".

They are named as follows: "test (1). txt", "test (2). txt", etc.

The problem that is occurring:

While running the loop while, the system moves a portion of the files, then I have to run again, then it moves another portion and then, it moves the last file, concluding the process with all the files in the "teste2 folder".

import shutil
import os

oldAdress = 'C:/Users/WJRS/Desktop/teste/' #pasta origem
newAdress = 'C:/Users/WJRS/Desktop/teste2/' #pasta destino

lista = os.listdir(oldAdress) #lista separando apenas os arquivos do caminho.

x = 0
#A função len() retorna o valor de 7, pois são 7 arquivos.
#No entanto, como se trata de uma lista, o indice a ser percorrido é de 0 a 6.
#por isso, 'x' começa em zero.
while x <= (len(os.listdir(oldAdress))-1):
    caminhoCompleto_old = oldAdress + lista[x] #variável recebe caminho + arquivo, conforme indice
    caminhoCompleto_new = newAdress + lista[x] #variável recebe caminho + arquivo, conforme indice
    shutil.move(caminhoCompleto_old, caminhoCompleto_new) #módulo 'shutil.move()' move os arquivos
    print(x, '-', lista[x]) #apenas para ver como está sendo feito
    x += 1

2 answers

1


This problem occurs due to call os.listdir() in the condition test of while:

while x <= (len(os.listdir(oldAdress))-1):

With each loop iteration, the file list length is recalculated and stays minor, as each file is moved, so the looping ends before transferring all the files.

The solution is to calculate the size of the list out of the loop while and store this value in a variable (which will be used in comparison of the looping).

Below is the corrected code:

import shutil
import os

oldAdress = 'C:/Users/WJRS/Desktop/teste/' #pasta origem
newAdress = 'C:/Users/WJRS/Desktop/teste2/' #pasta destino

lista = os.listdir(oldAdress) #lista separando apenas os arquivos do caminho.

# *** lista_len recebe o tamanho da lista ***
lista_len = len(lista)
x = 0

# *** Utilizar a variável ao invés de chamar 'os.listdir()' ***
while x < lista_len:
    caminhoCompleto_old = oldAdress + lista[x] #variável recebe caminho + arquivo, conforme indice
    caminhoCompleto_new = newAdress + lista[x] #variável recebe caminho + arquivo, conforme indice
    shutil.move(caminhoCompleto_old, caminhoCompleto_new) #módulo 'shutil.move()' move os arquivos
    print(x, '-', lista[x]) #apenas para ver como está sendo feito
    x += 1
  • 1

    Gomiero, thank you for your help! It worked perfectly!

0

__author__ = '@britodfbr'

import shutil
from os import listdir
from os.path import isfile, join, basename


def move(path_origem, path_destino, ext='zip'):
    for item in [join(path_origem, f) for f in listdir(path_origem) if isfile(join(path_origem, f)) and f.endswith(ext)]:
        #print(item)
        shutil.move(item, join(path_destino, basename(item)))
        print('moved "{}" -> "{}"'.format(item, join(path_destino, basename(item))))

if __name__ == '__main__':
    move('/tmp/a', '/tmp/b')

Exit:

moved "/tmp/a/file7.zip" -> "/tmp/b/file7.zip"
moved "/tmp/a/file4.zip" -> "/tmp/b/file4.zip"
moved "/tmp/a/file0.zip" -> "/tmp/b/file0.zip"
moved "/tmp/a/file3.zip" -> "/tmp/b/file3.zip"
moved "/tmp/a/file1.zip" -> "/tmp/b/file1.zip"
moved "/tmp/a/file6.zip" -> "/tmp/b/file6.zip"
moved "/tmp/a/file9.zip" -> "/tmp/b/file9.zip"
moved "/tmp/a/file2.zip" -> "/tmp/b/file2.zip"
moved "/tmp/a/file5.zip" -> "/tmp/b/file5.zip"
moved "/tmp/a/file10.zip" -> "/tmp/b/file10.zip"
moved "/tmp/a/file8.zip" -> "/tmp/b/file8.zip"
moved "/tmp/a/file01.zip" -> "/tmp/b/file01.zip"

Related to this link: en.stackoverflow.com/a/308147/62736

  • This does not provide an answer to the question. To criticize or request clarification from an author, leave a comment below its publication. - Of Revision

  • corrected! thanks.

Browser other questions tagged

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