在Python中,拷贝数据结构(如列表、字典、元组等)或文件可以通过以下几种方法实现:
数据结构拷贝
浅拷贝(Shallow Copy)
```python
import copy
original_list = [1, [2, 3], {'name': 'Python'}]
shallow_copy = copy.copy(original_list)
original_list = 5
print("原始列表:", original_list)
print("浅拷贝后:", shallow_copy)
深拷贝(Deep Copy)
```python
import copy
original_list = [1, [2, 3], {'name': 'Python'}]
deep_copy = copy.deepcopy(original_list)
original_list = 5
print("原始列表:", original_list)
print("深拷贝后:", deep_copy)
文件拷贝
使用`shutil`模块
```python
import shutil
shutil.copy('source.txt', 'destination.txt')
使用`os`模块
```python
import os
with open('source.txt', 'r') as source_file:
with open('destination.txt', 'w') as destination_file:
for line in source_file:
destination_file.write(line)
使用`copyfileobj`方法
```python
import shutil
with open('source.txt', 'rb') as fsrc, open('destination.txt', 'wb') as fdst:
shutil.copyfileobj(fsrc, fdst, length=1024)
使用`copytree`方法复制整个目录
```python
import shutil
shutil.copytree('source_directory', 'destination_directory')
以上方法适用于列表和文件的拷贝。对于列表,浅拷贝只复制对象的第一层,而深拷贝会递归地复制所有层级的对象。对于文件,`shutil`模块提供了多种方法,包括复制文件内容、复制文件元数据等。
请根据您的具体需求选择合适的方法进行操作