Handling java/python/c directories

Asked

Viewed 1,248 times

3

I have an A directory, and this A directory has several subdirectories, and in each subdirectory, it has a varied number of files. I would like to put all the files in a directory in the order they are in the subdirectories, some idea of how I can do this in java, python or c ?

2 answers

2


Hummm this kind of question in stackoverflow.com would be reported, since it’s not a question about a mistake or something, you’re simply asking someone to solve a problem for you. However as said here, this site is not stackoverflow.com. So I made a python script to help you since I was sleepless anyway.

create the copy.py file 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)

created the following structure to test in 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 will have 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 the file path+name and replaces the / for _ so that you can keep the files in order by name as if they were in the folder. note how in the commands tree files keep the same order even though they are no longer hierarchized by folders.

1

So that all this if the shutil solves your problem

import shutil
shutil.copytree(diretorioA, diretorioB, symlinks=False, ignore=None)

does exact and recursive copying of a directory. I’ve tried this on windows and linux and have no problem.

Browser other questions tagged

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