python - 如何在 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)
我无法使解压缩功能正常工作,有人可以帮助我吗?
谢谢
解决方案
该函数os.walk
不仅返回文件列表,而且即使返回,检查是否有 20 个文件也是由len(files) == 20
and not完成的files == 20
。您在评论中说所有文件都在同一个文件夹中(没有子目录),因此可以轻松完成os.listdir
:
files = os.listdir(Location)
if len(files) == 20:
do_something()
您在这里还有一些其他问题,例如循环文件以及checklist
我不确定是故意的,以及一些缩进问题,但这就是您的问题的答案。
推荐阅读
- php - 不带like()的按字母排序的查询 - laravel | 调用未定义的方法 Illuminate\Database\Query\Builder::LIKE()
- reactjs - 在父组件中的事件之后更新子组件中的道具?
- postgresql - 为什么 docker-entrypoint-initdb.d 中的脚本在数据库开始侦听导致 pg_restore 失败的连接之前运行?
- sql - 选择案例中多个组中用户的所有列
- javascript - 通过链接 Ng-Select(s) 过滤数据
- python - 如何检查我的 python 脚本是否以某种方式运行(使用某种调试器)
- vue.js - 在 VueJS 中弹出搜索结果页面
- python - 使用python的角谱方法
- swift - 如何在隐藏 NavBar 时禁用重新加载 CollectionView 的动画
- react-native - 在android应用程序中更新联系人列表的问题