Home > OS >  How do I copy the first layer of a folder structure in python?
How do I copy the first layer of a folder structure in python?

Time:06-21

Consider following folder structure

├─a
│  ├─a1
│  ├─a2
|      ├─a2_1
│      ├─a2_2
│  └─a3
│      ├─a3_1
│      ├─a3_2
│      └─a3_3

Is there any way to copy the folders a1, a2, a3 without any subfolders or files into a folder b so it would look like this:

├─b
│  ├─a1
│  ├─a2
|  └─a3

CodePudding user response:

If you don't want to copy subdirectories or files, you aren't really performing any copy at all. All you need to do is to create directories with same names as in the input folder.

import os

adir = 'a'
bdir = 'b'

for fn in os.listdir(adir):
    if os.path.isdir(os.path.join(adir, fn)):
      os.mkdir(os.path.join(bdir, fn))

CodePudding user response:

This should work

import os

for name in os.listdir("<PATH_TO_A>"):
    if os.path.isdir("<PATH_TO_A>"   name):
        os.mkdir("<PATH_TO_B>"   name)
  • Related