Python Shutil 模块:你应该知道的 10 种方法
首先,Python 中的 Shutil 模块提供了许多函数来对文件和文件集合执行高级操作。其次,它是一个内置模块,带有复制和删除文件和目录的自动化过程。第三,该模块还负责低级语义,例如创建、复制文件后关闭文件以及专注于业务逻辑。
python shutil 模块如何工作?
加载包
import shutil
查看包中的所有方法
print(dir(shutil))
[ 'chown', 'collections', 'copy', 'copy2', 'copyfile', 'copyfileobj', 'copymode', 'copystat', 'copytree', 'disk_usage', 'errno', 'fnmatch', 'get_archive_formats', 'get_terminal_size', 'get_unpack_formats', 'getgrnam', 'getpwnam', 'ignore_patterns', 'make_archive', 'move', 'nt', 'os', 'register_archive_format', 'register_unpack_format', 'rmtree', 'stat', 'sys', 'unpack_archive', 'unregister_archive_format', 'unregister_unpack_format', 'which']
使用 shutil 模块的基本语法如下:
import shutil
shutil.submodule_name(arguments)
文件目录操作
1. Python shutil.copy()
shutil.copy():此函数用于将源文件的内容或文本复制到目标文件或目录。它还保留文件的权限模式,但不保留文件的另一种类型的元数据,如文件的创建和文件的修改
import os
# import the shutil module
import shutil
# write the path of the file
path = '/home/User'
# List all the files and directories in the given path
print("Before copying file:")
print(os.listdir(path))
# write the Source path
source = "/home/User/file.txt"
# Print the file permission of the source given
perms = os.stat(source).st_mode
print("File Permission mode:", perms, "\n")
# Write the Destination path
destinationfile = "/home/User/file(copy).txt"
# Copy the content of source file to destination file
dests = shutil.copy(source, destinationfile)
# List files and directories of the path
print("After copying file:")
print(os.listdir(path))
# Print again all the file permission
perms = os.stat(destinationfile).st_mode
print("File Permission mode:", perms)
# Print path of of the file which is created
print("Destination path:", dests)
输出:
Before copying file:
['hrithik.png', 'test.py', 'file.text', 'copy.cpp']
File permission mode: 33188
After copying file:
['hrithik.png', 'test.py', 'file.text', 'file(copy).txt', 'copy.cpp']
File permission mode: 33188
Destination path: /home/User/file(copy).txt
解释:
在此代码中,首先,检查目录中存在的文件。其次,然后打印文件权限并提供文件的源路径。第三,将在新文件中为目标路径提供内容的副本。最后,再次打印目录中的所有文件,并检查是否创建了该文件的副本
2. Python shutil.copy2()
首先,这个函数就像 copy() 函数一样,除了它维护源文件的元数据。
from shutil import *
import os
import time
import sys
def show_file_info(filename):
stat_info = os.stat(filename)
print '\tMode :', stat_info.st_mode
print '\tCreated :', time.ctime(stat_info.st_ctime)
print '\tAccessed:', time.ctime(stat_info.st_atime)
print '\tModified:', time.ctime(stat_info.st_mtime)
os.mkdir('example')
print ('SOURCE time: ')
show_file_info('shutil_copy2.py')
copy2('shutil_copy2.py', 'example')
print ('DESTINATION time:')
show_file_info('example/shutil_copy2.py')
输出:
SOURCE time:
Mode : 33188
Created : Sat Jul 16 12:28:43 2020
Accessed: Thu Feb 21 06:36:54 2021
Modified: Sat Feb 19 19:18:23 2021
DESTINATION time:
Mode : 33188
Created : Mon Mar 1 06:36:54 2021
Accessed: Mon Mar 1 06:36:54 2021
Modified: Tue Mar 2 19:18:23 2021
解释:
在此代码中,我们编写了函数 copy2() 与副本相同,只是它执行了一个额外的操作来维护元数据。
3. Python shutil.copyfile()
在此函数文件中,将复制名称,这意味着原始文件由同一目录中的指定名称复制。它说该文件的副本存在于同一目录中。
import os
import shutil
print('BEFORE LIST:', os.listdir('.'))
shutil.copyfile('file_copy.py', 'file_copy.py.copy')
print('AFTER LIST:', os.listdir('.'))
输出:
Latracal:shutil Latracal$ python file_copy.py
BEFORE LIST:
[' .DS_Store', 'file_copy.py']
AFTER LIST:
[ .DS_Store', 'file_copy.py', 'file_copy.py.copy']
解释:
在此代码中,编写函数,为新文件复制相同的文件名
4. Python shutil.copytree()
此函数将一个目录中的文件和子目录复制到另一个目录
import pprint
import shutil
import os
shutil.copytree('../shutil', './Latracal')
pprint.pprint(os.listdir('./Latracal'))
输出:
Latracal:shutil Latracal$ clone—directory. py
[' .DS—Store' ,
'file_copy.py' ,
'file_copy_new.py'
'file_with_metadata.py' ,
'clone_directory. py']
解释:
写了函数 copytree(),以便我们可以获取该文件的副本。
5. Python shutil.rmtree()
此函数用于从指定目录中删除特定文件和子目录,这意味着该目录将从系统中删除。
import pprint
import shutil
import os
print('BEFORE:')
pprint.pprint(os.listdir('.'))
shutil.rmtree('Latracal')
print('\nAFTER:')
pprint.pprint(os.listdir('.'))
输出:
Latracal:shutil Latracal$ retove—dir.py
BEFORE:
['.DS_Store',
'file_copy.py',
'file_copy_new.py',
'remove_dir.py',
'copy_with_metadata.py',
'Latracal'
'clone_directory.py']
AFTER:
['.DS_Store',
'file—copy.py' ,
'file_copy_new.py',
'remove_dir.py',
'copy_with_metadata.py',
'clone_directory. py']
解释:
编写了函数 rmtree(),用于删除文件或目录。首先,列出了所有文件并应用了删除功能,然后再次列出了文件,以便查看文件是否 删除成功。
6. shutil.which()
用于查找机器中的文件路径,通过了解文件的路径轻松到达特定目的地。which()
import shutil
import sys
print(shutil.which('bsondump'))
print(shutil.which('no-such-program'))
输出:
Latracal:shutil Latracal$ python find_file.py
/usr/10ca1/mngodb@3.2/bin/bsondunp
解释:
可以在需要时找到任何文件。
7. shutil.disk_usage()
此函数用于通过调用 disk_usage() 函数来了解文件系统信息。
import shutil
total_mem, used_mem, free_mem = shutil.disk_usage('.')
gb = 10 **9
print('Total: {:6.2f} GB'.format(total_mem/gb))
print('Used : {:6.2f} GB'.format(used_mem/gb))
print('Free : {:6.2f} GB'.format(free_mem/gb))
输出:
shubhm:shutil shubhmS py
Total:499.9? GB
Used :187.72 GB
Free :3?8.26 GB
解释:
函数 disk_usage() 来了解总磁盘空间、已用磁盘空间和可用磁盘空间。
8. Python shutil.move()
此函数用于将文件和目录从一个目录移动到另一个目录,并将其从上一个目录中删除。也可以说重命名文件或目录。
import shutil
shutil.move('hello.py','newdir/')
输出:
'newdir/hello.py'
解释:
写了函数 move() 将文件或目录从一个位置移动到另一个位置。
9. shutil.make_archive()
此函数用于在根目录中构建文件的存档(zip 或 tar)。
import shutil
import pprint
root_directory='newdir'
shutil.make_archive("newdirabcd","zip",root_directory)
输出:
'C:\\python\\latracal\\newdirabcd.zip'
解释:
在此代码中,我们编写了 functionmake_archive(),告诉他们根目录的名称以在根目录中构建文件存档。
10. shutil.get_archive_formats()
提供了文件或目录中所有支持的存档格式。
import shutil
import sys
shutil.get_archive_formats()
输出:
[('bztar', "bzip2'ed tar-file"), ('gztar', "gzip'ed tar-file"), ('tar', 'uncompressed tar file'), ('xztar', "xz'ed tar-file"), ('zip', 'ZIP file')]
解释:
函数 get_archive_formats() 来获取文件或目录中支持的存档格式。
优势
- shutil 模块可帮助您自动复制文件和目录。
- 该模块在没有实际处理时保存打开、读取、写入和关闭文件的步骤,只需移动文件即可。