首页 > 解决方案 > 如何在 Python 中解压文件?

问题描述

我正在做一个项目,如果文件夹中的文件正好等于 20,文件就会被压缩。但如果没有 20 个文件,则会发送一封电子邮件。

这是我的代码:

import zipfile
import shutil
import subprocess
import glob
import os
import time
from subprocess import Popen
# Import smtplib for the actual sending function
import sys
from email.mime.text import MIMEText
import smtplib
import ssl


port = 587  # For starttls
smtp_server = "SMTP.office365.com"
sender_email = "XXX.com"
receiver_email = "XXX.com"
password = 'XXX'
message = """\
Subject: Hi there

there are no 20 files in XXX
"""

context = ssl.create_default_context()
Location = 'XXX'
checklist = glob.glob(Location + '*.zip')

    for files in os.walk(Location):
        if files == 20:
              for filename in checklist:
                  zf = zipfile.ZipFile(filename, 'r')
                  NewName = filename.replace(Location, '')
                  NewName = NewName.replace('.ZIP', '')
                  zf.extractall(Location + "Unzipped\\")
                  os.rename(Location + 'Unzipped\\ZSNP_M36_Q0006_00000.xls', Location + 'Unzipped\\' + NewName + '.xls')

    p = Popen("Macro_SSC_csv_conversion_batch.bat", cwd=r"XXX")
    stdout, stderr = p.communicate()
    print(p.returncode)
        else:
              with smtplib.SMTP(smtp_server, port) as server:
                   server.ehlo()  # Can be omitted
                   server.starttls(context=context)
                   server.ehlo()  # Can be omitted
                   server.login(sender_email, password)
                   server.sendmail(sender_email, receiver_email, message)


我无法使解压缩功能正常工作,有人可以帮助我吗?

谢谢

标签: python

解决方案


该函数os.walk不仅返回文件列表,而且即使返回,检查是否有 20 个文件也是由len(files) == 20and not完成的files == 20。您在评论中说所有文件都在同一个文件夹中(没有子目录),因此可以轻松完成os.listdir

files = os.listdir(Location)
if len(files) == 20:
    do_something()

您在这里还有一些其他问题,例如循环文件以及checklist我不确定是故意的,以及一些缩进问题,但这就是您的问题的答案。


推荐阅读