The ZipFile module is a Python specialized file packaging module that should be used in conjunction with the os.path() module when packing files

directory

    • Zipfile.zipfile ()
    • Write () in Zipfile
    • OS. Walk (path) method
    • Compress all files in this path
    • Compress only specific files in folders

Recently Python has become a hot topic on social media, and many of my friends from other fields have come to ask me about learning Python, especially in the office automation field.

However, there is no denying that Python’s obvious advantages in the field of office automation are also undeniable. Today I happened to use Python to compress files automatically, and I will write about it here.

We often compress files in our daily work, and then send them to the mailbox, etc., and compress files is a good backup process for files. So today, the big Bad Cov will talk about file compression in Python.

The third module used to compress files in Python is the ZipFile module, which, as the name suggests, is designed for file compression.

Some points to note when using the ZipFile module to compress files:

Zipfile.zipfile ()

This module works somewhat like os.open(), which opens a file or folder and creates one if it doesn’t; Zipfile.zipfile () opens a zipfile, or creates one if it doesn’t. Same as os.open() : add ‘w’ or ‘a’ to each argument, and write accordingly.

Here’s the code:

Zipfile. Zipfile (' Text.zip', 'w')# Open the text.zip file in write mode, create it if it doesn't exist
Copy the code

` `

Write () in Zipfile

Again, this method is similar to the os.write() method in that it writes to the file.

It’s worth noting, however, that the write() method under Zipfile writes to a folder or file, not a single line of text or content.

Like this line of code:

zipfiles.write(filenames)
Write the file under Filenames in zipFiles
Copy the code

Here, the Wolf suggests that the argument passed in parentheses for write() should be the absolute path to the file. The purpose is to make it easier for the program to compress the file and not fail to find the file.

OS. Walk (path) method

Another important method is os.walk (),

The os.walk(path) method passes in the absolute path of a folder and returns three values:

  1. A string of the current folder name
  2. A list of strings for subfolders of the current file
  3. A list of strings for files in the current folder

With these three questions figured out, it’s time to write code,

When we compress files, sometimes we want to compress the entire folder, and sometimes we want to compress certain types of files in the folder, such as all the.txt files in the file.

Therefore, in order to facilitate the direct call of friends, I wrote the two cases in two functions respectively. When calling the function, you only need to pass in the path of the folder you want to compress.

Compress all files in this path

import os
import zipfile
path1 = ‪ 'D: \ DMP'

# File compression function
def fileToZip(path) :
    path = path.split('\ \')
    path[0] = path[0] [-2: len(path[0])]
    path = '/'.join(path)
    number = 1

    while (True):
        fileName = os.path.basename(path1) + '_' + str(number) + '.zip'
        if not os.path.exists(fileName):
            break
        number += 1

    zipfiles = zipfile.ZipFile(fileName, 'w')

    for foldername, subfolder, filename in os.walk(path):
        print('Folder: %s' % (foldername))
        for subfoldername in subfolder:
            print('Subfolder: %s/%s' % (foldername, subfoldername))
            #zipfiles.write(os.path.join(foldername, subfoldername))
        for filenames in filename:
            print('Subfile: %s/%s' % (foldername, filenames))
            #if filenames. Endswith ('.txt')
            zipfiles.write(os.path.join(foldername, filenames))
    zipfiles.close()
fileToZip(path1)
Copy the code

Compress only specific files in folders

In the code, you can modify the statement into other files, such as.py, XLSX, etc

import os
import zipfile
path1 = ‪ 'D: \ DMP'


# File compression function
def fileToZip(path) :
    path = path.split('\ \')
    path[0] = path[0] [-2: len(path[0])]
    path = '/'.join(path)
    number = 1

    while (True):
        fileName = os.path.basename(path1) + '_' + str(number) + '.zip'
        if not os.path.exists(fileName):
            break
        number += 1

    zipfiles = zipfile.ZipFile(fileName, 'w')

    for foldername, subfolder, filename in os.walk(path):
        print('Folder: %s' % (foldername))
        for subfoldername in subfolder:
            print('Subfolder: %s/%s' % (foldername, subfoldername))
            #zipfiles.write(os.path.join(foldername, subfoldername))
        for filenames in filename:
            print('Subfile: %s/%s' % (foldername, filenames))
            
            Check if it is a.txt file.
            if filenames.endswith('.txt') :Check whether the file has a. TXT suffix
                zipfiles.write(os.path.join(foldername, filenames))
    zipfiles.close()


fileToZip(path1)	# call function
Copy the code

The first three lines of the function are a small processing done by the Wolf to avoid the path being passed in the \ U202a format. \ U202a error, 90% do not know the secret hidden in the file path! (Dry goods collection)

Feel good remember to like attention yo!

At the same time, you can also follow my wechat official account.The Wolf hole Lord“Get more fun and useful Python project sharing and more Internet information!

Big bad Wolf is looking forward to progress with you!