How to access folders and copy files in Python?

Asked

Viewed 548 times

1

Hi, I’m new to Python. I have a folder "MAIN". Inside this folder there are several other folders. In these folders I have the file "IQ.jpg". I wonder how I do to access all the folders inside the MAIN folder and copy the "IQ.jpg" files to another "NOVA_PASTA" folder, at the same time that it copies, I would like it to rename the file to the name of the folder that it was pulled. For example

The file "IQ.jpg" is in the folder "Meus_calculos", this folder is inside the folder "MAIN". When the "IQ.jpg" file is copied to the "NOVA_PASTA" folder, I would like the program to rename this file to "IQ-Meus_calculos.jpg"

Basically I would like the program to go through all the folders, copy the files and rename them according to the name of the folder from which it was removed so there is no duplication of files in the folder, since in all the folders has the file with the same name and extension. It would be possible to do this?

Here’s the code I tried

from shutil import copy
from pathlib import Path
import os


src = Path(r".\D:\Usuarios\0025429\Desktop\old_folder")
filename = "IQ"
dst = Path(r".\D:\Usuarios\0025429\Desktop\new_folder")
idx = 0

directory_list = list()
for root, dirs, files in os.walk(r"D:\Usuarios\0025429\Desktop\old_folder", topdown=False):
    for name in dirs:
        directory_list.append(os.path.join(root, name))
print(directory_list)

for file in src.iterdir():
    if file.is_file() and file.stem == filename:
        idx += 1
        copy(file, (dst / f"Archive_{idx}").with_suffix(file.suffix))
insira o código aqui

1 answer

0


import os
import shutil
  • There are two ways to move and rename, see:

In this part, the file will be renamed and moved

os.rename("diretorio/origem/nome-do-arquivo", "diretorio/destino/novo-nome-arquivo")

Using shutil, you can move the file

shutil.move("diretorio/origem/nome-do-arquivo", "diretorio/lugar-para-onde-sera-movida/novo-nome-do-arquivo")
  • Using this method you spoke above, how would I get my program to enter multiple folders and copy the files? NOTE: has 1 folder with several folders inside.

  • You can use the python glob library https://docs.python.org/3/library/glob.html, so you can pick up the files recursively inside the folders, just pass the file pattern, for example: .txt

  • thanks for the help

  • It’s pretty cool the answer - I would suggest exploring the "pathlib" bible and using objects "pathlib. Path" to trabalahr with the names, and even with the copy of the files - the code becomes more concise and easy to maintain. Want to take a look?

Browser other questions tagged

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