Python中的Shutil模块提供了许多对文件和文件集合进行高级操作的函数。它属于Python的标准实用程序模块。此模块有助于自动执行文件和目录的复制和删除过程。
shutil.copy2()
Python中的方法用于将源文件的内容复制到目标文件或目录。此方法与shutil.copy()
方法,但它还会尝试保留文件的元数据。
源必须代表文件,但目标可以是文件或目录。如果目标是目录,则文件将使用源中的基本文件名复制到目标中。另外,目的地必须是可写的。如果目标是文件并且已经存在,则将其替换为源文件,否则将创建一个新文件。
用法: shutil.copy2(source, destination, *, follow_symlinks = True)
参数:
source:代表源文件路径的字符串。
destination:代表目标文件或目录路径的字符串。
follow_symlinks(可选):此参数的默认值为True。如果为False,并且source表示符号链接,则它将尝试将所有元数据从源符号链接复制到newly-created目标符号链接。此函数取决于平台。
Note:参数列表中的“ *”表示以下所有参数(此处为“ follow_symlinks”)仅是关键字参数,可以使用其名称(而不是位置参数)来提供。
返回类型:此方法返回一个表示新创建文件路径的字符串。
代码1:使用shutil.copy2()方法将文件从源复制到目标
# Python program to explain shutil.copy2() method
# importing os module
import os
# importing shutil module
import shutil
# path
path = '/home/User/Documents'
# List files and directories
# in '/home/User/Documents'
print("Before copying file:")
print(os.listdir(path))
# Source path
source = "/home/User/Documents/file.txt"
# Print the metadeta
# of source file
metadata = os.stat(source)
print("Metadata:", metadata, "\n")
# Destination path
destination = "/home/User/Documents/file(copy).txt"
# Copy the content of
# source to destination
dest = shutil.copy2(source, destination)
# List files and directories
# in "/home / User / Documents"
print("After copying file:")
print(os.listdir(path))
# Print the metadata
# of the destination file
matadata = os.stat(destination)
print("Metadata:", metadata)
# Print path of newly
# created file
print("Destination path:", dest)
输出:
Before copying file: ['hrithik.png', 'test.py', 'sample.txt', 'file.text', 'copy.cpp'] Metadata: os.stat_result(st_mode=33188, st_ino=801113, st_dev=2056, st_nlink=1, st_uid=1000, st_gid=1000, st_size=84, st_atime=1558866178, st_mtime=1558866156, st_ctime=1558866156) After copying file: ['hrithik.png', 'test.py', 'sample.txt', 'file.text', 'file(copy).txt', 'copy.cpp'] Metadata: os.stat_result(st_mode=33188, st_ino=801111, st_dev=2056, st_nlink=1, st_uid=1000, st_gid=1000, st_size=84, st_atime=1558866178, st_mtime=1558866156, st_ctime=1558933947) Destination path: /home/User/Documents/file(copy).txt
代码2:如果目的地是目录
# Python program to explain shutil.copy2() method
# importing os module
import os
# importing shutil module
import shutil
# Source path
source = "/home/User/Documents/file.txt"
# Destination path
destination = "/home/User/Desktop/"
# Copy the content of
# source to destination
dest = shutil.copy2(source, destination)
# List files and directories
# in "/home / User / Desktop"
print("After copying file:")
print(os.listdir(destination))
# Print path of newly
# created file
print("Destination path:", dest)
输出:
After copying file: ['input.txt', 'GeeksForGeeks', 'output.txt', 'file.txt', 'web.py', 'tree.cpp'] Destination path: /home/User/Desktop/file.txt
代码3:使用shutil.copy2()方法时可能出现的错误
# Python program to explain shutil.copy2() method
# importing shutil module
import shutil
# If the source and destination
# represents the same file
# 'SameFileError' exception
# will be raised
# If the destination is
# not writable
# 'PermissionError' exception
# will be raised
# Source path
source = "/home/User/Documents/file.txt"
# Destination path
destination = "/home/User/Documents/file.txt"
# Copy the content of
# source to destination
shutil.copy2(source, destintion)
输出:
Traceback (most recent call last): File "try.py", line 26, in dest = shutil.copy(source, destination) File "/usr/lib/python3.6/shutil.py", line 241, in copy2 copyfile(src, dst, follow_symlinks=follow_symlinks) File "/usr/lib/python3.6/shutil.py", line 104, in copyfile raise SameFileError("{!r} and {!r} are the same file".format(src, dst)) shutil.SameFileError: '/home/User/Desktop/file.txt' and '/home/User/Desktop/file.txt' are the same file
代码4:使用shutil.copy2()方法处理错误
# Python program to explain shutil.copy2() method
# importing shutil module
import shutil
# Source path
source = "/home/User/Documents/file.txt"
# Destination path
destination = "/home/User/Documents/file.txt"
# Copy the content of
# source to destination
try:
shutil.copy2(source, destination)
print("File copied successfully.")
# If source and destination are same
except shutil.SameFileError:
print("Source and destination represents the same file.")
# If there is any permission issue
except PermissionError:
print("Permission denied.")
# For other errors
except:
print("Error occurred while copying file.")
输出:
Source and destination represents the same file.
参考: https://docs.python.org/3/library/shutil.html
相关用法
- Python os.dup()用法及代码示例
- Python next()用法及代码示例
- Python set()用法及代码示例
- Python object()用法及代码示例
- Python bytes()用法及代码示例
- Python os.times()用法及代码示例
- Python os.chmod用法及代码示例
- Python hash()用法及代码示例
- Python os.ftruncate()用法及代码示例
- Python os.truncate()用法及代码示例
- Python os.fsdecode()用法及代码示例
- Python dict pop()用法及代码示例
- Python os.abort()用法及代码示例
- Python os.WEXITSTATUS()用法及代码示例
注:本文由纯净天空筛选整理自ihritik大神的英文原创作品 Python | shutil.copy2() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。