我有一个结构如下的文件夹(A):
A\b
A\c
A\d
我想像这样将文件夹b,c和d向下复制3次:
A\b\b1\b2\b3
A\c\c1\c2\c3
A\d\d1\d2\d3
其中b1,b2和b3是文件夹b的副本,c和d也是如此。
当我运行下面的代码时,我最终得到所需的结构,但还在每个子文件夹中添加了三个副本,因此A \ b \ b1包含b1,b2和b3文件夹。问题与循环有关,但我无法查明问题
import os
import sys
import shutil
list1= [1,2,3]
path = "C:\ladg\oner"
root, dirs, files = os.walk(path).next()
for dir in dirs:
for i in list1:
new_folder_path = os.path.join(root,dir, dir+ str(i))
shutil.copytree(os.path.join(root, dir), new_folder_path)
答案 0 :(得分:2)
尝试一下。您当前正在遍历列表,而无需更改目录。
import os
import sys
import shutil
list1= [1,2,3]
path = "C:\ladg\oner"
root, dirs, files = os.walk(path).next()
for dir in dirs:
curr_path = os.path.join(root, dir)
for i in list1:
new_folder_path = os.path.join(curr_path, dir + str(i))
shutil.copytree(curr_path, new_folder_path)
os.chdir(new_folder_path)
curr_path = new_folder_path
在后续问题中,如果您想实现具有此结果目录的方案:
A
-- b
-- b1
-- b2
-- b3
-- c
-- c1
-- c2
-- c3
您可以使用以下代码。这与第一个建议不同,因为现在您要创建一个tmp_dir
来存储副本,然后最终用这个新的curr_dir
替换旧的tmp_dir
。在执行后续副本时,必须维护curr_dir
的完整副本。
import os
import sys
import shutil
list1= [1,2,3]
path = "~/A"
root, dirs, files = os.walk(path).next()
for dir in dirs:
curr_dir = os.path.join(root, dir)
tmp_dir = os.path.join(root, "tmp_" + dir)
os.mkdir(tmp_dir)
for i in list1:
new_folder_path = os.path.join(tmp_dir, dir+ str(i))
shutil.copytree(curr_dir, new_folder_path)
shutil.rmtree(curr_dir)
shutil.move(tmp_dir, curr_dir)
答案 1 :(得分:0)
基本策略是将原始目录(例如b
)复制到目录tmp_b
(具有唯一名称)。将其复制到b1
和b1\b2
,然后将临时副本移动到b1\b2\b3
以下是实现此目的的代码:
#!/usr/bin/env python3
import os, sys, shutil
import tempfile
def make_nested_copies(path, N):
root, dirs, _ = next(os.walk(path))
for current_dir_name in dirs:
temp = tempfile.mkdtemp()
temp_path = os.path.join(temp, current_dir_name)
destination_path = os.path.join(root, current_dir_name)
shutil.copytree(destination_path, temp_path)
for i in range(1,N):
destination_path = os.path.join(destination_path, current_dir_name + str(i))
shutil.copytree(temp_path, destination_path)
destination_path = os.path.join(destination_path, current_dir_name + str(N))
shutil.move(temp_path, destination_path)
if __name__ == '__main__':
make_nested_copies(sys.argv[1], 3)
使用以下目录结构进行测试:
A
|-- A.txt
|-- b
| `-- b.txt
|-- c
| `-- c.txt
`-- d
`-- d.txt
结果:
A
|-- A.txt
|-- b
| |-- b.txt
| `-- b1
| |-- b.txt
| `-- b2
| |-- b.txt
| `-- b3
| `-- b.txt
|-- c
| |-- c.txt
| `-- c1
| |-- c.txt
| `-- c2
| |-- c.txt
| `-- c3
| `-- c.txt
`-- d
|-- d.txt
`-- d1
|-- d.txt
`-- d2
|-- d.txt
`-- d3
`-- d.txt