[Python] arsenal shutil, os, zipfile: three-piece organizing files

Here Insert Picture Description


A, shutil module

1. Copy and rename files and folders

【01】 shutil.copy (source, destination)

Copy the file path at the source to the destination path of the folder; if the destination is a file name, it will be duplicated as a new file name.

import shutil

shutil.copy(r'E:\【05】编程设计\Python\Python自动化办公\测试\文件夹1\hello.txt',
	r'E:\【05】编程设计\Python\Python自动化办公\测试\文件夹2')
shutil.copy(r'E:\【05】编程设计\Python\Python自动化办公\测试\文件夹1\hello.txt',
	r'E:\【05】编程设计\Python\Python自动化办公\测试\文件夹2\你好.txt')    # 复制并改名

That is, through shutil.copy () function, we can achieve a single file copy and rename operation.

【02】 shutil.copytree (source, destination)

shutil.copy () is a file copy, and shutil.copytree () capable of copying the entire folder, including the files and folders within folders.

import shutil

#【01】文件和文件夹的复制与改名
shutil.copytree(r'E:\【05】编程设计\Python\Python自动化办公\测试\文件夹1', 
	r'E:\【05】编程设计\Python\Python自动化办公\测试\文件夹3')   # 实际相当于创建了一个新文件夹

——

2. move files and folders to be renamed

【01】shutil.move(source, destination)

By using shutil.move () function, we can achieve move with renamed files and folders. When using this function, you should note the following:

  1. A source document is, Where do you want is already existing folder B, the file is moved to the folder A B; if the file exists in the folder, it will be overwritten.
  2. A source file, file B Where do you want a tape path, the file A will be moved to the lower path and renamed B.
  3. A source file, file B Where do you want the same directory, the file is renamed file B. A

If the source is a folder A, then follow the above routine can be substituted for, the principle is the same.

import shutil

#【02】文件和文件夹的移动与改名
shutil.move(r'E:\【05】编程设计\Python\Python自动化办公\测试\文件夹3\hello.txt',
	r'E:\【05】编程设计\Python\Python自动化办公\测试\文件夹4')
shutil.move(r'E:\【05】编程设计\Python\Python自动化办公\测试\文件夹3\hello.txt',
	r'E:\【05】编程设计\Python\Python自动化办公\测试\文件夹4\你好.txt')
shutil.move(r'E:\【05】编程设计\Python\Python自动化办公\测试\文件夹3\hello.txt',
	r'E:\【05】编程设计\Python\Python自动化办公\测试\文件夹3\hello.txt')

——

3. To permanently delete files and folders

Using the os module, we can achieve delete a file or an empty folder; but the use of shutil module, we may permanently (irreversibly) to delete a folder and all its contents.

  • os.unlink (path) will remove the path of the file (single)
  • os.rmdir (path) will remove the path of the folder (blank)
  • shutil.rmtree (path) will remove the path of the folder containing all files and folders, including folders

Be sure to note that, shutil.rmtree () will irreversibly delete files permanently, so use them have to be extremely careful.

That there is no more delete methods? If we do not accidentally delete a file requires a method that can be recovered?

Yes, that is used to delete send2trash module.

——

4. Safely Remove module send2trash

send2trash third-party module, it is much safer than conventional Python delete function, it will send the files and folders to your computer's trash or recycle bin, delete and non-permanent.

Then we can choose to permanently delete or restore files and folders on your computer recycle bin.

To use send2trash, we must first be installed.

Open a command prompt, enter pip install send2trash

import send2trash

#【04】用send2trash模块安全删除
baconFile = open('bacon.txt','a')       # 创建txt文件
baconFile.write('Bacon is not a vegatable')   # 文件中写入内容
baconFile.close()
send2trash.send2trash('bacon.txt')   # 用send2trash删除文件

Here Insert Picture Description

Two, os.walk () to traverse the directory tree

Sometimes we need to traverse the entire folder, such as folder to rename all files in a folder, including all subfolders of the folder in the folder.

This time we need to use os.walk () function, for combined cycle operation can be achieved traversing the directory tree.

os.walk (path) passing a file path character string in each iteration of the loop will return three values.

  1. String name of the current folder
  2. A list of the current folder subfolders strings
  3. List of strings in the current folder file

It is worth focusing reminded that the so-called current folder means that for the current iteration of the loop folder.

import shutil

for folderName, subfolders, filenames in os.walk(r'E:\【05】编程设计\Python\Python自动化办公\【09】组织文件\delicious'):
	print('当前文件夹:'+folderName) 
	print('包含子文件夹:', end='')
	for subfolder in subfolders:
		print(subfolder, end=' ') 

	print()

	print('包含文件:', end='')
	for filename in filenames:
		print(filename, end=' ')

	print('\n-------------------------------------------')

Show results
Here Insert Picture Description
Here Insert Picture Description

Three, zipfile module

1. Read the ZIP file

For compression bag of files and folders, how to operate the process? You should use the zipfile module.

To read the contents of the ZIP file, you must first create a ZipFile object.

import zipfile

#【01】读取ZIP文件
exampleZip = zipfile.ZipFile('example.zip')     # 创建ZIP对象
print(exampleZip.namelist())        # 返回ZIP中所有文件和文件夹的列表

spamInfo = exampleZip.getinfo('spam.txt')    # 获取ZIP的单个内容
print(spamInfo.file_size)               # 原文件大小
print(spamInfo.compress_size)     # 压缩后文件大小

c_ratio = round(spamInfo.file_size/spamInfo.compress_size, 2)  # 计算压缩率
print(c_ratio)

Run the code, look at the results
Here Insert Picture Description

Summarize the methods and properties:

  • zipfile.ZipFile () to create a ZIP objects
  • namelist () returns a list of strings ZIP file of all the files and folders
  • getInfo () returns an object of a particular file ZipInfo
  • File_size properties of the original file size
  • The size of the compressed file attribute compress_size
  • close () Closes the ZIP file

——

2. Extract the ZIP file

About decompress ZIP files can have two functions:

  • extractall () from a ZIP file, unzip all the files and folders
  • extract () decompress a single ZIP file from the specified file
import zipfile, os

#【02】从ZIP文件中解压缩
exampleZip.extractall()               # 将所有文件和文件夹解压到当前工作目录中,括号中可指定文件夹名
exampleZip.extract('spam.txt', r'E:\【05】编程设计\Python\Python自动化办公') # 将指定文件解压到指定文件夹(文件夹不存在则创建)
exampleZip.close()

——

3. Create and add the ZIP file

To create a new ZIP file, you must be "write mode" or "add mode" open ZipFile object that is passed in the second parameter.

import zipfile, os
#【03】创建和添加到ZIP文件
newZip = zipfile.ZipFile('new.zip','w')     # 以"写模式"或者"添加模式"创建,这里'w'表示写模式
newZip.write('spam.txt', compress_type=zipfile.ZIP_DEFLATED)   # 第二参数为压缩类型参数,可以总是设置为该值

newZip.close()

Here Insert Picture DescriptionHere Insert Picture Description

Published 35 original articles · won praise 35 · views 2739

Guess you like

Origin blog.csdn.net/nilvya/article/details/104353383