Move python files to another folder in another directory

Asked

Viewed 1,417 times

0

Friends, I need to move a file to another folder in another directory after renaming it in Python. I’m a beginner in Python and may lack a little vision to solve the problem. I tried to move when renaming with.Rename, shutil and nothing!

The question is : How to move this file I just renamed to another folder in another directory?

arquivo = os.rename(arqu, pedido+'.pdf')

Follow the complete code .

import PyPDF2
import os
import shutil

os.chdir(r'C:\Users\1\Desktop\Escaneados')

for f in os.listdir():
    arqu = (f)
print(arqu)

reader = PyPDF2.PdfFileReader(arqu,'rb')  # Importar arquivo
p = reader.getPage(0)
texto = p.extractText()

pos = texto.find("LC")  # Palavra para pesquisar
pedido = (texto[pos:pos + 8])  # +8 caracteres

pos2 = texto.find("Cliente")
cliente = (texto[pos2:pos2 + 40])


arquivo = os.rename(arqu, pedido+'.pdf')

1 answer

2

You can move and rename in a single command, both with the os.rename as with the shutil.move

import os 
import shutil

# Movendo e renomeando com os.rename
os.rename('diretorio/origem/nome-arquivo', 'diretorio/destino/novo-nome-arquivo')

# Movendo e renomeando com shutill
shutil.move('diretorio/origem/nome-arquivo', 'diretorio/destino/novo-nome-arquivo')

See that just change the name of the file in the destination directory so that beyond the move, the operation of rename is executed. In both cases the destination directory must already exist. In windows, if there is, in the destination directory, a file with the same name for the new file, an exception will be raised.

Note that according to the documentation, shutil.move() uses os.rename() when the destination is in the actual purchasing system in which the function is executed, otherwise the source file is copied using shutil.copy2() to the destination and then is removed.

Browser other questions tagged

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