if __name__ == "__main__": source_directory = "/path/to/source/folder" destination_directory = "/path/to/destination/folder"
时间: 2025-06-28 19:09:58 浏览: 14
### Python 脚本实现文件夹复制或同步
为了实现从 `source_directory` 到 `destination_directory` 的文件夹复制或同步操作,可以利用 Python 中的 `shutil` 和 `os` 库来完成这一功能。下面提供了一个简单的例子:
#### 使用 shutil.copytree 进行完整的目录复制
当目标是执行一次性的完整复制时,`shutil.copytree()` 是最简便的方法之一。
```python
import os
import shutil
def copy_entire_folder(source_directory, destination_directory):
try:
shutil.copytree(source_directory, destination_directory)
print(f"Successfully copied {source_directory} to {destination_directory}")
except FileExistsError:
print("Destination already exists.")
except Exception as e:
print(f"An error occurred while copying: {e}")
copy_entire_folder('/path/to/source', '/path/to/dest')
```
此方法适用于初次设置环境或是需要保留所有历史版本的情况[^1]。
#### 实现增量同步逻辑
对于更复杂的场景,比如只希望同步更新过的文件而不是每次都做完全拷贝,则可以通过比较源路径和目的路径下的文件修改时间戳来进行判断并仅传输发生变化的部分。
```python
import os
from pathlib import Path
import hashlib
import shutil
def hash_file(file_path):
"""Generate MD5 checksum of a given file."""
hasher = hashlib.md5()
with open(file_path, 'rb') as f:
buf = f.read(65536)
while len(buf) > 0:
hasher.update(buf)
buf = f.read(65536)
return hasher.hexdigest()
def sync_folders(source_dir, dest_dir):
for root, dirs, files in os.walk(source_dir):
relative_root = os.path.relpath(root, source_dir)
# Create corresponding directories in the destination folder.
current_dest_dir = os.path.join(dest_dir, relative_root)
if not os.path.exists(current_dest_dir):
os.makedirs(current_dest_dir)
for name in files:
src_file = os.path.join(root, name)
dst_file = os.path.join(current_dest_dir, name)
should_copy = False
# If destination file doesn't exist or has different content (based on hashes), then we need to update it.
if not os.path.isfile(dst_file) or hash_file(src_file) != hash_file(dst_file):
should_copy = True
if should_copy:
shutil.copy2(src_file, dst_file) # Copy including metadata like timestamps.
sync_folders('/path/to/source', '/path/to/dest')
```
上述代码通过计算每个文件的内容哈希值来决定是否应该覆盖现有文件,从而实现了更加精细控制的同步过程.
阅读全文
相关推荐



















