Python Shutil模块

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 shutil

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

Let’s see the output for this program:

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

Python shutil Copy file

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 shutil

os.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:

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

python shutil Copy file to new directory

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 time

def 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)

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 os

shutil.copytree('../shutil', './journaldev')

print('\nAFTER:')
pprint.pprint(os.listdir('./journaldev'))

Let’s see the output for this program:

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

python shutil Copy directory recursively

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 os

print('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目录位于当前文件夹中。 运行脚本后,它将与内容一起删除。 让我们看一下该程序的输出:

python shutil Remove file and directory tree

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 shutil

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

Let’s see the output for this program:

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

Finding a file on PATH

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 shutil

total_b, used_b, free_b = shutil.disk_usage('.')

gb = 10 ** 9

print('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

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)

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值