Manipulation Directories java/python/c

Question:

I have a directory A, and this directory A has several subdirectories, and in each subdirectory, it has different amounts of files. I would like to put the files all in one directory in the order they are in the subdirectories, any ideas how I can do this in java, python or c ?

Answer:

Hmmm this kind of question on stackoverflow.com would be reported, since it's not a question about an error or anything like that, you're simply asking someone to solve a problem for you. However as stated here , this site is not stackoverflow.com. So I made a python script to help you since I was not sleepy anyway.

create the file copia.py with the following code:

import os
import sys

origem = sys.argv[1]
destino = sys.argv[2]

if not os.path.exists(destino):
    os.makedirs(destino)

for raiz, subDiretorios, arquivos in os.walk(origem):
    for arquivo in arquivos:
        arqCaminho = os.path.join(raiz, arquivo)
        novoArqNome = "%s/%s" % (destino, arqCaminho.replace('/', '_'))
        os.rename(arqCaminho, novoArqNome)

I created the following structure to test in the dirA folder:

$ tree dirA/
dirA/
├── arq1.foo
├── subDir1
│   ├── arq1.foo
│   ├── arq2.foo
│   ├── arq3.foo
│   ├── arq4.foo
│   └── subSubDir1
│       ├── arq1.foo
│       └── arq2.foo
├── subDir2
│   └── arq1.foo
└── subDir3
    ├── arq1.foo
    ├── arq2.foo
    └── arq3.foo

you run the script as follows:

$python copia.py dirA/ destino

and you get the following result:

$ tree destino/
destino/
├── dirA_arq1.foo
├── dirA_subDir1_arq1.foo
├── dirA_subDir1_arq2.foo
├── dirA_subDir1_arq3.foo
├── dirA_subDir1_arq4.foo
├── dirA_subDir1_subSubDir1_arq1.foo
├── dirA_subDir1_subSubDir1_arq2.foo
├── dirA_subDir2_arq1.foo
├── dirA_subDir3_arq1.foo
├── dirA_subDir3_arq2.foo
└── dirA_subDir3_arq3.foo

note that I renamed the file with path+filename and replaced the / with _ so that you can keep the files in order by name as if they were in the folder. note how in the tree commands the files keep the same order even though they are no longer hierarchized by folders.

Scroll to Top