python 拷贝_python粘贴共享文件夹

python 拷贝_python粘贴共享文件夹在 Python 中 你可以使用 shutil 模块来拷贝文件夹及其内容 以下是两种常见的拷贝方式 1 拷贝整个文件夹 包括子目录和文件 pythonimport osimport shutil source path os path abspath E Projects source dir target path os path abspath E

在Python中,你可以使用`shutil`模块来拷贝文件夹及其内容。以下是两种常见的拷贝方式:

1. 拷贝整个文件夹(包括子目录和文件):

python

import os

import shutil

source_path = os.path.abspath('E:\\Projects\\source_dir')

target_path = os.path.abspath('E:\\Projects\\new_folder\\target_dir')

如果目标路径不存在,则创建

if not os.path.exists(target_path):

os.makedirs(target_path)

使用shutil.copytree()函数拷贝整个目录

shutil.copytree(source_path, target_path)

print('copy dir finished!')

2. 遍历源文件夹,拷贝所有文件到目标文件夹:python

import os

import shutil

source_path = os.path.abspath('E:\\Projects\\source_dir')

target_path = os.path.abspath('E:\\Projects\\new_folder\\target_dir')

如果目标路径不存在,则创建

if not os.path.exists(target_path):

os.makedirs(target_path)

遍历源文件夹

for item in os.listdir(source_path):

src_item = os.path.join(source_path, item)

dst_item = os.path.join(target_path, item)

如果是文件,则直接复制

if os.path.isfile(src_item):

shutil.copy2(src_item, dst_item)

如果是文件夹,则递归调用copy_dir函数

elif os.path.isdir(src_item):

copy_dir(src_item, dst_item)

def copy_dir(src, dst):

if not os.path.exists(src):

return

if not os.path.exists(dst):

os.mkdir(dst)

pathes = os.listdir(src)

for p in pathes:

f_path = os.path.join(src, p)

dst_path = f_path.replace(src, dst)

if os.path.isfile(f_path):

shutil.copy2(f_path, dst_path)

elif os.path.isdir(f_path):

copy_dir(f_path, dst_path)

以上代码示例展示了如何使用`shutil.copytree()`函数来拷贝整个文件夹,以及如何遍历文件夹并递归地拷贝所有文件和子文件夹。使用`shutil.copy2()`函数可以在拷贝文件的同时保留文件的数据(如时间戳)。

请根据你的具体需求选择合适的拷贝方法

编程小号
上一篇 2025-02-06 18:42
下一篇 2026-03-14 20:28

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/73809.html