When you need to work with high-level file operations like copying contents of a file, create a new copy of a file and archiving it, Python shutil module is the way to go.

当您需要进行高级文件操作(例如复制文件内容,创建文件的新副本并进行归档)时,Python shutil模块是您的理想之选。

Python关闭 (Python shutil)

Python shutil module enables us to operate with file objects easily and without diving into file objects a lot. It takes care of low-level semantics like creating file objects, closing the files once they are copied and allows us to focus on the business logic of our program. Let’s see shutil module in action here.

Python shutil模块使我们能够轻松处理文件对象,而无需大量研究文件对象。 它负责处理低级语义,例如创建文件对象,在复制文件后关闭文件,并使我们能够专注于程序的业务逻辑。 让我们在这里看到shutil模块的作用。

Python Shutil示例 (Python shutil example)

Let’s look into different examples to understand shutil module.

让我们看一下不同的示例来了解shutil模块。

拷贝文件 (Copy File)

Using shutil’s copyfile() function, it is easy to copy a file to a new file in current directory only.

使用shutil的copyfile()函数,很容易仅将文件复制到当前目录中的新文件。

Here is a sample program on how we can make a new clone of existing file in our current directory:

这是一个示例程序,说明如何在当前目录中创建现有文件的新克隆:

import os
import shutilprint('BEFORE:', os.listdir('.'))
shutil.copyfile('file_copy.py', 'file_copy.py.copy')
print('AFTER:', os.listdir('.'))

Let’s see the output for this program:

让我们看一下该程序的输出:

Copy file to current directory

将文件复制到当前目录

Note that copyfile() function takes name of the new file to be created.

请注意, copyfile()函数采用要创建的新文件的名称。

将文件复制到另一个目录 (Copying Files to another directory)

Using shutil’s copy() function, it is easy to copy a file to another directory.

使用shutil的copy()函数,可以很容易地将文件复制到另一个目录。

Let’s look at a code snippet on how this can be done:

让我们看一下如何做到这一点的代码片段:

import os
import shutilos.mkdir('journaldev')
print('BEFORE:', os.listdir('journaldev'))
shutil.copy('file_copy.py', 'journaldev')
print('AFTER:', os.listdir('journaldev'))

Let’s see the output for this program:

让我们看一下该程序的输出:

Copy file to new directory

将文件复制到新目录

This function is different from copyfile() function as the later takes a file name as a parameter whereas the copy() function takes directory name as an input.

此函数与copyfile()函数不同,后者在以后将文件名作为参数,而copy()函数将目录名作为输入。

Finally, the permissions of the file are also cloned when copying a file with both the functions but metadata is not copied, which means that new file created will have a freshly created time instead of the original file’s time.

最后,在复制具有两个功能的文件时,文件权限也会被克隆 ,但不会复制元数据,这意味着创建的新文件将具有新创建的时间,而不是原始文件的时间。

使用元数据复制文件 (Copying file with Metadata)

If you need to make an exact clone of the file, along with the permissions and the metadata of a file as well, we can make use of the copy2() function. Note that this might not work completely on a POSIX based system.

如果您需要对文件进行精确的克隆,以及文件的权限和元数据,我们可以使用copy2()函数。 请注意,这可能无法在基于POSIX的系统上完全工作

Here is a sample program on how we use this function::

这是有关如何使用此功能的示例程序:

import os
import shutil
import timedef file_metadata(file_name):stat_info = os.stat(file_name)print('  Mode    :', oct(stat_info.st_mode))print('  Created :', time.ctime(stat_info.st_ctime))print('  Accessed:', time.ctime(stat_info.st_atime))print('  Modified:', time.ctime(stat_info.st_mtime))os.mkdir('journaldev')
print('SOURCE FILE:')
file_metadata('file_copy.py')shutil.copy2('file_copy.py', 'journaldev')print('DESTINATION FILE:')
file_metadata('journaldev/file_copy.py')

We run this function on a POSIX system so only the Mode of the file and Modified date is preserved:

我们在POSIX系统上运行此功能,因此仅保留文件的模式和修改日期

Copy File Metadata (as much as possible)

复制文件元数据(尽可能多)

On other systems, even the created and accessed time would have matched exactly.

在其他系统上,即使创建和访问的时间也将完全匹配。

复制完整目录 (Replicating complete directory)

With copytree() function, it is possible to completely replicate a directory tree recursively. This means that if there are more directories inside a directory, that directory will be cloned as well.

使用copytree()函数,可以递归完全复制目录树。 这意味着,如果目录中有更多目录,该目录也将被克隆。

Let’s look at a code snippet on how we can clone a complete directory:

让我们看一下如何克隆完整目录的代码片段:

import pprint
import shutil
import osshutil.copytree('../shutil', './journaldev')print('\nAFTER:')
pprint.pprint(os.listdir('./journaldev'))

Let’s see the output for this program:

让我们看一下该程序的输出:

Copy directory recursively

递归复制目录

Note that we do not print the directory journaldev contents before as the directory name copytree() function takes as input must not exist before running this command.

请注意,我们之前不会打印目录journaldev内容,因为在运行此命令之前,目录名copytree()函数作为输入必须不存在

删除目录 (Removing a Directory)

Another simplest example with shutil is removing complete directory. No need to recursively remove files or close file handling connections.

带有shutil另一个最简单的示例是删除完整目录。 无需递归删除文件或关闭文件处理连接。

Here is a sample program on how easy it is with rmtree() function:

这是一个示例程序,说明使用rmtree()函数有多么容易:

import pprint
import shutil
import osprint('BEFORE:')
pprint.pprint(os.listdir('.'))shutil.rmtree('journaldev')print('\nAFTER:')
pprint.pprint(os.listdir('.'))

Here, we print contents of current directory. Before running the script, the journaldev directory exists in current folder. After running the script, it is deleted along with the contents. Let’s see the output for this program:

在这里,我们打印当前目录的内容。 运行脚本之前, journaldev目录位于当前文件夹中。 运行脚本后,它将与内容一起删除。 让我们看一下该程序的输出:

Remove complete directory tree

删除完整的目录树

查找文件 (Finding files)

The which() function presents an excellent tool to find a file on your machine which is present on the PATH.

which()函数提供了一个很好的工具,可以在您的计算机上找到PATH中存在的文件。

Here is a sample program with a file example:

这是一个带有文件示例的示例程序:

import shutilprint(shutil.which('bsondump'))
print(shutil.which('no-such-program'))

Let’s see the output for this program:

让我们看一下该程序的输出:

Finding a file on PATH

在PATH上查找文件

监视文件系统空间 (Monitoring File-system Space)

We can even get information about how much is present on our file system with simplete call using disk_usage() function.

我们甚至可以使用disk_usage()函数通过disk_usage()调用来disk_usage()有关文件系统中存在多少信息。

Here is a sample program:

这是一个示例程序:

import shutiltotal_b, used_b, free_b = shutil.disk_usage('.')gb = 10 ** 9print('Total: {:6.2f} GB'.format(total_b / gb))
print('Used : {:6.2f} GB'.format(used_b / gb))
print('Free : {:6.2f} GB'.format(free_b / gb))

Let’s see the output for this program:

让我们看一下该程序的输出:

File System Space

文件系统空间

结论 (Conclusion)

In this lesson, we studied how we can work with high-level file operations like copying contents of a file, create a new copy of a file etc. without diving into complex File Handling operations with shutil module in Python.

在本课程中,我们研究了如何使用高级文件操作(如复制文件内容,创建文件的新副本等),而又不shutil使用Python中的shutil模块进行复杂的文件处理操作。

Read more Python posts here.

在此处Python帖子。

下载源代码 (Download the Source Code)

Download all Python scripts for this lesson下载本课程的所有Python脚本

翻译自: https://www.journaldev.com/20536/python-shutil-module

Python Shutil模块相关推荐

  1. python shutil模块用法实例分析_Python shutil模块用法实例分析

    分享大神指教Python中的shutil模块的rmtree()方法如分享大神指教Python中的shutil模块的rmtree()方法如何实现.思路是怎样的rmtree() 是用来删除文件目录及其中的 ...

  2. Python shutil 模块详解

    Python shutil 模块详解 1.模块介绍 2.copytree 示例 3.move 示例 1.模块介绍 import shutil# copy data from file-like obj ...

  3. 以写代学:python shutil模块

    在python交互解释器中导入shutil模块,一起来简单了解一下shutil模块,shutil是shell utility的缩写,shell实用工具 可以查看帮助 shutil(help)      ...

  4. python shutil模块导入_python常用模块之shutil模块

    python常用模块之shutil模块 shutil模块,高级的文件.文件夹.压缩包处理模块 1.shutil.copyfile(src,des[,length]):将文件内容拷贝到另一个文件 In ...

  5. python shutil模块用法实例分析_python之shutil模块使用方法(三分钟了解)

    文章目录 shutil模块 1.1简介 shutil模块提供了一些针对文件和目录,压缩包的高级操作,主要是拷贝.移动.对于单个文件的操作,可参考os模块的用法. 1.2 作用及作用范围 作用: 快速的 ...

  6. Python - shutil模块(2)——压缩目录、文件

    打包目录 1 #_*_coding:utf-8_*_ 2 #__author__ = "csy" 3 import shutil 4 5 shutil.make_archive(& ...

  7. python shutil模块安装_python shutil模块

    1.复制文件和文件夹 调用 shutil.copy(source, destination),将路径 source 处的文件复制到路径 destination处的文件夹( source 和 desti ...

  8. python shutil_[转]Python shutil 模块

    转自: https://www.cnblogs.com/wuzhiblog/p/6535527.html https://www.cnblogs.com/caibao666/p/6433864.htm ...

  9. Python中os和shutil模块实用方法集锦

    Python中os和shutil模块实用方法集锦 类型:转载 时间:2014-05-13 这篇文章主要介绍了Python中os和shutil模块实用方法集锦,需要的朋友可以参考下 复制代码代码如下: ...

最新文章

  1. 3ds Max V-Ray5 完整指南大师班视频教程
  2. 嵌入式linux dhcp移植,嵌入式linux中的dhcp服务器
  3. python3调用函数len结果不返回字符串长度_Python通过len函数返回对象长度
  4. 神经网络第三部分:网络Neural Networks, Part 3: The Network
  5. 善待精力,保持体力,保持热情
  6. c#endread怎么打印出来_打印机打印出来是白板是怎么回事
  7. Lockdoor Framework:一套自带大量网络安全资源的渗透测试框架
  8. 什么是Python脚本?
  9. 拓端tecdat|基于出租车GPS轨迹数据的研究:出租车行程的数据分析
  10. web项目设计文档_web项目前后端分离模式下的权限设计方案
  11. Win11更新补丁导致应用程序崩溃错误代码0xc0000135怎么解决?
  12. 一、绘制不同类别特征均值标准差直方图
  13. windows下解决弹窗广告
  14. SecureCRT远程操作linux系统
  15. 神州优车粗暴裁员:人与人之间最起码的尊重呢?
  16. 工业设计公司常对设计有什么要求?
  17. 手机投屏电脑,无需第三方软件,鼠标控制手机
  18. QNX Neutrino RTOS简介
  19. AMA预告|章鱼加速器如何在熊市助力 Web3 创业
  20. 【Azure Data Platform】ETL工具(21)——Azure Databricks使用(1)——访问Azure Blob

热门文章

  1. [Machine Learning Algorithm] 决策树与迭代决策树(GBDT)
  2. SQL2008-显示表大小行数
  3. verilog中的initial块、always块详细解释
  4. PyQt5-QTextEdit控件使用
  5. 拼多多服务端实习生笔试-滑动窗口2018/4/3
  6. const的理解、const指针、指向const的指针
  7. android之datepicker控件用法
  8. ADT版本不同导致的一个问题
  9. hdu 4421(枚举+2-sat)
  10. zoj 2706 线段树