Moving files in folders

Asked

Viewed 240 times

0

I have a folder called test.

Inside this folder there are 1000 subfolders from 1 to 1000.

Within each of these subfolders there is another folder called Reports

Inside each folder Reports there is a file called report json.

I need to get every one of these files report json. and moves them to the folder fate.

I have the following script:

import shutil
import os
import glob

source = "C:\\Users\\usuario\\Desktop\\teste\\**numero_da_pasta**\\reports\\"
dest1 = dst = "C:\\Users\\usuario\\Desktop\\destino\\"

files = os.listdir(source)

for f in files:
    if f == "report.json":
        shutil.move(source+f, dest1)

It is able to move the report.json file to the destination folder, but every time I have to manually modify the number_da_folder to 2, 3, 4 etc...

How do I get this process all automated? I’m not getting it done.

1 answer

2


To change the folder name just use the following function:

os.rename(old, new)

from what I understand Voce wants to number the destination folder, correct?

In your case it would be something like:

import shutil
import os
import glob

source = "C:\\Users\\usuario\\Desktop\\teste\\**numero_da_pasta**\\reports\\"
dest1 = dst = "C:\\Users\\usuario\\Desktop\\destino\\"

files = os.listdir(source)
i = 1
for f in files:
    if f == "report.json":
        shutil.move(source+f, dest1)
    os.rename(dest1 + "destino", dest1 + "destino" + str(i))
    i += 1
  • Thanks @Clayton Tosatti I guess I couldn’t explain my problem well, but with the logic you proposed I managed to make it work. Thank you very much!

  • great Danilo! Dispose ;)

Browser other questions tagged

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