1. What is shutil
shutil can be simply understood as sh util
#, meaning shell tool. The shutil module is a supplement to the os module and is mainly used for copying, deleting, moving, compressing and decompressing files.
2. Main methods of shutil module
1. shutil.copyfileobj(fsrc, fdst[ , length=16*1024])
Copy the content of the file to another file, and you can copy the content of the specified size. This method is the basis for other copy methods in the shutil module. Other methods essentially call this method.
Let us take a look at its source code:
def copyfileobj(fsrc, fdst, length=16*1024): while 1: buf = fsrc.read(length) if not buf: break fdst.write(buf)
The code is very simple and can be understood at a glance. But please note that fsrc and fdst are file objects opened using the open() method.
import shutil s =open('fsrc.txt','r') d=open('fdst.txt','w') shutil.copyfileobj(s,d,length=16*1024)
##2. shutil.copyfile(src, dst)
Copy file
shutil.copyfile('f1.log', 'f2.log') #目标文件无需存在
3. shutil.copymode(src, dst)
Copy permission only. The content, groups, and users remain unchanged
shutil.copymode('f1.log', 'f2.log') #目标文件必须存在
4. shutil.copystat(src, dst)
Only copy status information, including: mode bits, atime, mtime, flagsshutil.copystat('f1.log', 'f2.log') #目标文件必须存在
5. shutil.copy(src, dst)
拷贝文件和权限
import shutil shutil.copy('f1.log', 'f2.log')
6. shutil.copy2(src, dst)
拷贝文件和状态信息
import shutil shutil.copy2('f1.log', 'f2.log')
7. shutil.copytree(src, dst, symlinks=False, ignore=None)
递归的去拷贝文件夹
src:源文件夹
dst:复制至dst文件夹,该文件夹会自动创建,需保证此文件夹不存在,否则将报错
symlinks:是否复制软连接,True复制软连接,False不复制,软连接会被当成文件复制过来,默认False
ignore:忽略模式,可传入
ignore_patterns()
copy_function:拷贝文件的方式,可以传入一个可执行的处理函数,默认为copy2,Python3新增参数
ignore_dangling_symlinks:sysmlinks设置为False时,拷贝指向文件已删除的软连接时,将会报错,如果想消除这个异常,可以设置此值为True。默认为False,Python3新增参数。
import shutil,os folder1 = os.path.join(os.getcwd(),"aaa") # bbb与ccc文件夹都可以不存在,会自动创建 folder2 = os.path.join(os.getcwd(),"bbb","ccc") # 将"abc.txt","bcd.txt"忽略,不复制 shutil.copytree(folder1,folder2,ignore=shutil.ignore_patterns("abc.txt","bcd.txt"))
8. shutil.rmtree(path[, ignore_errors[, onerror]])
递归的去删除文件
import shutil shutil.rmtree('folder1')
9. shutil.move(src, dst)
递归的去移动文件,它类似mv命令,其实就是重命名。
import shutil shutil.move('folder1', 'folder3')
10.shutil.make_archive(base_name, format[, root_dir[, base_dir, verbose, dry_run, owner, group, logger])
创建压缩包并返回文件路径,例如:zip、tar
创建压缩包并返回文件路径,例如:zip、tar
-
base_name:压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
<br/>
如 data_bak 保存至当前路径如:/tmp/data_bak =>保存至/tmp/
format:压缩包种类,“zip”, “tar”, “bztar”,“gztar”
-
root_dir:要压缩的文件夹路径(默认当前目录)
owner:用户,默认当前用户
group:组,默认当前组
logger:用于记录日志,通常是logging.Logger对象
<br/>
把当前目录下的文件压缩生成copy.zip文件到当前目录下注意:此操作会出现递归拷贝压缩导致文件损坏(当前目录下的copy.zip中会有copy.zip)
import shutil shutil.make_archives('D:\copy3\copy','zip',base_dir='D:\copy2\\测试.txt')
把D:\copy2\测试.txt文件压缩,在D:\copy3\路径下生成copy.zip。
import shutilshutil.make_archives('copy','zip')
三、总结
本文主要介绍了Python中shutil模块,对模块中主要的方法进行了详细的介绍。对遇到的问题进行详细的解答。最后使用Python编程语言,通过在实际开发中的项目。方便大家对shutil模块的认知。希望对大家的学习有帮助。
The above is the detailed content of An article will guide you through the shutil module in Python. For more information, please follow other related articles on the PHP Chinese website!

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Chinese version
Chinese version, very easy to use