Reputation: 1484
Am trying to copy subdirectories from directory but I realize the first subfolder copied is copied 'recursively'. I would not like that. I would like to copy the sub folder intactly.
import os
import shutil
#---- Create the directries
os.makedirs("Test/Dir-A/Sub-dir-A")
os.makedirs("Test/Dir-A/Sub-dir-B")
os.makedirs("Test/Dir-B/Sub-dir-A")
os.makedirs("Test/Dir-B/Sub-dir-B")
os.makedirs("Test/Dir-C/Sub-dir-A")
os.makedirs("Test/Dir-C/Sub-dir-B")
selectdirs = ["Dir-A", "Dir-B"]
alldirs = os.listdir("Test")
specificcourses = [folder for folder in alldirs if folder in selectdirs]
for f in specificcourses:
shutil.move(os.path.join("Test", f), os.path.join("Test", "New-dir"))
When I run the code, I have Sub-dir-A, Sub-dir-B and Dir-B copied in New-dir. I however want Dir-A and Dir-B in New-dir.
Upvotes: 0
Views: 44
Reputation: 131
You need to make sure that your "New-dir" exists before copying.
This works as you may want:
import os
import shutil
#---- Create the directries
os.makedirs("Test/Dir-A/Sub-dir-A")
os.makedirs("Test/Dir-A/Sub-dir-B")
os.makedirs("Test/Dir-B/Sub-dir-A")
os.makedirs("Test/Dir-B/Sub-dir-B")
os.makedirs("Test/Dir-C/Sub-dir-A")
os.makedirs("Test/Dir-C/Sub-dir-B")
selectdirs = ["Dir-A", "Dir-B"]
alldirs = os.listdir("Test")
specificcourses = [folder for folder in alldirs if folder in selectdirs]
os.makedirs("Test/New-dir")
for f in specificcourses:
input()
shutil.move(os.path.join("Test", f), os.path.join("Test", "New-dir"))
Upvotes: 1
Reputation:
import os
import re
#---- Create the directries
try:
os.makedirs("Test/Dir-A/Sub-dir-A")
os.makedirs("Test/Dir-A/Sub-dir-B")
os.makedirs("Test/Dir-B/Sub-dir-A")
os.makedirs("Test/Dir-B/Sub-dir-B")
os.makedirs("Test/Dir-C/Sub-dir-A")
os.makedirs("Test/Dir-C/Sub-dir-B")
except:
pass
sub = (os.walk("Test"))
try:
os.mkdir("NewDir")
except:
pass
for f in sub:
for s in f[1]:
os.mkdir(re.sub("^Test", "NewDir", os.path.join(f[0], s)))
Upvotes: 1