首页 > 编程知识 正文

Python 中的shutil模块

时间:2023-11-25 15:30:22 阅读:309265 作者:WSXE

在本教程中,我们将学习 Python 中的 shutil模块。我们将讨论如何执行高级文件操作,例如创建一个新的复制文件并将其归档,以及使用 Python 脚本将内容从一个文件复制到另一个文件。让我们对 shutil模块有一个基本的介绍。

Python Shutil Module

Python shutil 模块提供了执行高级文件操作的工具。它可以操作文件对象,并为我们提供复制和删除文件的能力。它处理低级语义,如在执行所有操作后创建和关闭文件对象。

shutil模块的工作

Python shutil 模块附带了许多内置方法。我们将探索一些重要的方法。要开始使用这个模块,首先我们需要将它导入到当前的 Python 文件中。

复制文件

本模块提供复制()功能,用于将数据从一个文件复制到另一个文件。文件必须在同一个目录中,并且目标文件必须是可写的。让我们理解下面的语法。

语法-


shutil.copyfile(source, destination, *, follow_symlinks = True)

参数:

在上面的语法中-

  • 第一个参数是 source,它显示源文件的路径。
  • 第二个参数是 destination,它显示目标文件的路径。
  • 第三个参数是可选的;此参数的默认值为真。
  • 它返回一个字符串,显示新创建的文件的路径。

让我们理解下面的例子。

示例-


import os
import shutil

# Creating a new folder in the current directory
os.mkdir('javatpoint')

# It will show the empty folder
print('Empty Folder:', os.listdir('javatpoint'))

# testcompare.py file will be copied in the javatpoint folder
shutil.copy('testcompare.py', 'javatpoint')

# After coping the file folder shows the file
print('File Copied Name:', os.listdir('javatpoint'))

输出:

Empty Folder: []
File Copied Name: ['testcompare.py']

解释-

copy()函数以目录名作为参数。这里元数据不复制,复制的文件将被认为是新创建的文件。此方法还克隆了文件的所有权限。需要注意的一点是,如果目标文件已经存在,它将被源文件替换。

让我们看另一个例子。

示例- 2 如果目的地是目录


import os
import shutil

# hello.txt file will be copied 
source = r'D:Python Projectjavatpointhello.txt'

# In the newly created foloder
destination = r'D:Python ProjectNewFile'

# Storing the new path of hello.txt file
dest = shutil.copy(source, destination)

# Print the new path
print(dest)

输出:

D:Python ProjectNewFilehello.txt

正如我们提到的,copy()函数不复制元数据。但是,我们将使用 copy2() 函数,该函数允许我们复制文件,包括其元数据。

示例- 3:使用复制方法时的错误处理


# importing shutil module
import shutil

# It is a source path
source = r"D:Python ProjectNewFolder"

# It is a destination path
destination = r"D:Python ProjectNewFolder"

try:
    shutil.copy(source, destination)
    print("File copied successfully.")

# If the given source and path are same
except shutil.SameFileError:
    print("Source and destination represents the same file.")

# If there is no permission to write
except PermissionError:
    print("Permission denied.")

# For other errors
except:
    print("Error occurred while copying file.")

输出:

Source and destination represents the same file.

copy2()函数

该功能类似于复制()功能。它还可以将一个文件的内容复制到另一个文件,但唯一的区别是它可以保留文件的元数据。让我们理解下面的语法。

语法:


shutil.copy2(source, destination, *, follow_symlinks = True)

参数:

在上面的语法中-

  • 第一个参数是 source,它显示源文件的路径。
  • 第二个参数是 destination,它显示目标文件的路径。
  • 第三个参数是可选的;此参数的默认值为真。
  • 它返回一个字符串,显示新创建的文件的路径。

让我们理解下面的例子。

示例-


import os
import shutil

# hello.txt file will be copied 
source = r'D:Python Projectjavatpointhello.txt'

metadata = os.stat(source)
print(metadata)

# In the newly created foloder
destination = r'D:Python ProjectNewFile'
# Storing the new path of hello.txt file

dest1 = shutil.copy2(source, destination)
metadata = os.stat(dest1)

print("After copying file")
print(metadata)

# Print the new path
print(dest1)

输出:

os.stat_result(st_mode=33206, st_ino=562949953459285, st_dev=3029671014, st_nlink=1, st_uid=0, st_gid=0, st_size=17, st_atime=1622815671, st_mtime=1622705607, st_ctime=1622705607)
After copying file
os.stat_result(st_mode=33206, st_ino=562949953459287, st_dev=3029671014, st_nlink=1, st_uid=0, st_gid=0, st_size=17, st_atime=1622815748, st_mtime=1622705607, st_ctime=1622706243)
D:Python ProjectNewFilehello.txt

shutil.copyfile()函数

此方法用于将源文件的内容复制到除元数据之外的目标文件。源和目标必须有文件,目标文件必须提供写权限。如果目标文件已经存在,那么它将被新文件替换,否则创建新文件。

让我们看看下面的语法。

语法:


shutil.copyfile(source, destination, *, follow_symlinks = True)

参数:

在上面的语法中-

  • 第一个参数是 source,它显示源文件的路径。
  • 第二个参数是 destination,它显示目标文件的路径。
  • 第三个参数是可选的;此参数的默认值为真。
  • 它返回一个字符串,显示新创建的文件的路径。

让我们理解下面的例子。

示例-


import shutil

# hello.txt file will be copied 
source = r'D:Python Projectjavatpointhello.txt'

# In the newly created foloder
destination = r'D:Python ProjectNewFilehi.txt'
# Storing the new path of hello.txt file

dest1 = shutil.copyfile(source, destination)

# Print the new path
print(dest1)

输出:

D:Python ProjectNewFilehi.txt

shutil.copytree()函数

此方法用于复制完整的目录。它将从源位置开始的整个目录树复制到目标目录。目标目录必须不存在。让我们看看下面的语法。

语法:


shutil.copytree(src, dst, symlinks = False, ignore = None, copy_function = copy2, igonre_dangling_symlinks = False)

参数:

在上面的语法中:

  • src - 显示源目录的路径。
  • dest - 显示目的目录的路径。
  • 符号链接(可选)- 它采用布尔值-真和假。这取决于原始链接或链接的元数据将被复制到新的树中。
  • 忽略(可选)- 默认情况下为无,但如果忽略被传递,它必须是一个可调用的接收作为其参数。copytree()访问该目录。
  • copy_function(可选)-copy 2 是该参数的默认值。复制()功能可用作参数。
  • 忽略 悬空 符号链接(可选)- 此参数用于在符号链接指向的文件不存在时引发异常。
  • 它返回代表新创建的目录路径的字符串。

示例-


# importing shutil module
import shutil

# It is source path
src = r'D:Python Projectjavatpoint'

# It is destination path
dest = r'D:Python ProjectNewFolder'

# Copy the content of
# source to destination
dest1 = shutil.copytree(src, dest)

# Now we print path of newly
# created file
print("Destination path:", dest1)

输出:

Destination path: D:Python ProjectNewFolder

shutil.rmtree()

此方法用于删除完整的目录树。让我们看看下面的语法。

语法:


shutil.rmtree(path, ignore_errors=False, onerror=None)

参数-

在上面的语法中-

  • 路径- 表示文件路径。类似路径的对象是字符串或字节对象。
  • 忽略 _ 错误- 如果该参数为真,则删除将被忽略。
  • onerror - 如果 ignore_errors 为 false,则通过调用 onerror 指定的处理程序来处理此类错误。

让我们理解下面的例子-

示例-


import shutil
import os

# location
location_dir = r"D:Python ProjectNewFile"

# directory
directory = r"D:Python Projectjavatpoint"

# path
path1 = os.path.join(location_dir, directory)

# removing directory
shutil.rmtree(path1)

上面的代码将删除给定的目录。

shutil.which()函数

shutil . what()函数用于获取可执行应用的路径,如果调用给定的 cmd,该程序将运行。它在给定的路径中找到文件。让我们看看下面的语法。

语法:


shutil.which(cmd, mode = os.F_OK | os.X_OK, path = None)

参数

在上面的语法中-

  • cmd - 是表示文件的字符串。
  • 模式- 指定执行方法的文件模式。
  • 路径- 此参数指定要使用的路径。
  • 此方法返回可执行应用的路径。

让我们理解下面的例子。

示例-


# importing shutil module
import shutil

# search the file
cmd = 'python'

# Using shutil.which() method
locating = shutil.which(cmd)

# Print result
print(locating)

输出:

C:Pythonpython.EXE

它将在计算机中找到给定的文件,如果找到文件,它将返回文件的路径,否则返回无。


版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。