关于python:python-文件解压

10次阅读

共计 1263 个字符,预计需要花费 4 分钟才能阅读完成。

申请网络 zip 资源, 下载后解压,并拷贝解压后的文件内容到粘贴板

from pyperclip import copy
import zipfile
from os import rename
import os
import shutil
import requests
import getpass

download_dir = os.path.join(os.environ['HOME'] + os.sep, "Downloads")
# download_dir = getpass.getuser() + os.sep + 'Downloads'
request_url = 'http://xxxx.com/a.zip'


file_name = download_dir + os.sep + 'xxx.zip'
unzip_finder = download_dir + os.sep + 'xxx'


if os.path.exists(file_name):
    os.remove(file_name)


if os.path.isdir(unzip_finder):
    shutil.rmtree(unzip_finder)


# 解压
def unzip_file(zip_src,dst_dir):
    dst_dir = [dst_dir if dst_dir.endswith(os.sep) else dst_dir + os.sep][0]
    with zipfile.ZipFile(zip_src, 'r') as fd:
        for zfile in fd.namelist():
            gbkfilename = zfile.encode('cp437').decode('GBK')
            fd.extract(zfile, dst_dir)
            rename(''.join([dst_dir, zfile]),''.join([dst_dir, gbkfilename]))

# 申请资源并解压复制内容到粘贴板
def fetch_jets():
    request = requests.get(request_url)
    if request.status_code == 200:
        with open(file_name, 'wb') as f:
            f.write(request.content)
        unzip_file(file_name, unzip_finder)
        name1 = [unzip_finder + os.sep + f.title() for f in os.listdir(unzip_finder) if f.title().startswith('你懂得?')][0]
        # name1 = [unzip_finder + os.sep + f.title() for f in os.listdir(unzip_finder) if f.title().find('你懂得?') > 0][0]
        with open(name1, 'r', encoding='utf-8') as f:
            content = f.read()
            copy(content)
            print('Congratulations!!!')
    else:
        print('网络申请出错...')

fetch_jets()
正文完
 0