我正在一个项目中,如果一个文件夹中的文件恰好等于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)
我无法使用解压缩功能,有人可以帮我吗?
谢谢
答案 0 :(得分:0)
函数os.walk
不仅返回文件列表,即使返回了文件,也要检查其中是否有20个文件是由len(files) == 20
而不是files == 20
完成的。您在评论中说,所有文件都在同一个文件夹中(没有子目录),因此可以轻松地通过os.listdir
完成:
files = os.listdir(Location)
if len(files) == 20:
do_something()
您在这里还有其他问题,例如遍历文件和不确定的checklist
,还有一些缩进问题,但这就是您在这里所提问题的答案。