3.编写一个程序,可复制整个目录下的所有内容到另一个目录下,包含原目录下的所有子目录和文件。
时间: 2024-03-03 12:48:14 浏览: 17
你可以使用Python中的shutil模块来实现这个功能。下面是一个示例代码,可以将源目录下的所有内容复制到目标目录下。
```python
import os
import shutil
def copy_files(source_dir, target_dir):
if not os.path.exists(target_dir):
os.makedirs(target_dir)
for item in os.listdir(source_dir):
source_file = os.path.join(source_dir, item)
target_file = os.path.join(target_dir, item)
if os.path.isdir(source_file):
copy_files(source_file, target_file)
else:
shutil.copy2(source_file, target_file)
source_dir = "/path/to/source/dir"
target_dir = "/path/to/target/dir"
copy_files(source_dir, target_dir)
```
在上面的代码中,首先判断目标目录是否存在,如果不存在则创建。然后遍历源目录下的所有内容,如果是文件夹则递归调用copy_files函数,如果是文件则使用shutil.copy2函数将其复制到目标目录下。