Python - Moving files to another folder

1

Could someone give me a help in the code below?

Goal: Move files from one folder to another.

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

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

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

The problem that is occurring:

When executing the while loop, the system moves a portion of the files, then it has to execute again, then it moves another portion and then it moves the last file, completing the process with all the files in the "test2" 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
    
asked by anonymous 21.04.2018 / 19:29

2 answers

0

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

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

At each loop iteration, the length of the file list is recalculated and becomes smaller as each file is moved, so looping ends before transferring all files.

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

The following 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
    
21.04.2018 / 21:03
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')

Output:

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: http://stackoverflow.com/a/308147/62736

    
19.06.2018 / 15:21