简体   繁体   English

批处理文件解压文件并运行 Python 脚本

[英]Batch file to unzip files and run Python script

I have a project where I need to unzip files containing a .xls file and then run a Python script to convert the file to .xlsx .我有一个项目,我需要解压缩包含.xls文件的文件,然后运行 ​​Python 脚本将文件转换为.xlsx I need to do this by executing a Windows Batch file through the Windows Task Scheduler.我需要通过 Windows 任务计划程序执行 Windows 批处理文件来做到这一点。 I found some code on Superuser to unzip the file, but it does not loop and you have to explicitly type the name of the file you want to unzip.我在 Superuser 上找到了一些解压缩文件的代码,但它不会循环,您必须明确键入要解压缩的文件的名称。

Here's the unzip code:这是解压代码:

@echo off
setlocal
cd /d %~dp0
Call :UnZipFile "C:\Test Folder\" "C:\Test Folder\File1.zip"
exit /b

:UnZipFile <ExtractTo> <newzipfile>
IF "%~dp0"=="" GOTO Continue
set vbs="%temp%\_.vbs"
if exist %vbs% del /f /q %vbs%
>%vbs%  echo Set fso = CreateObject("Scripting.FileSystemObject")
>>%vbs% echo If NOT fso.FolderExists(%1) Then
>>%vbs% echo fso.CreateFolder(%1)
>>%vbs% echo End If
>>%vbs% echo set objShell = CreateObject("Shell.Application")
>>%vbs% echo set FilesInZip=objShell.NameSpace(%2).items
>>%vbs% echo objShell.NameSpace(%1).CopyHere(FilesInZip)
>>%vbs% echo Set fso = Nothing
>>%vbs% echo Set objShell = Nothing
cscript //nologo %vbs%
if exist %vbs% del /f /q %vbs%

Here's my Python code:这是我的 Python 代码:

import win32com.client as win32
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--sourcefilepath')
parser.add_argument('--sourcefilename')
args = parser.parse_args()

fname = r"{sourcefilepath}{sourcefilename}".format(sourcefilepath=args.sourcefilepath,sourcefilename=args.sourcefilename)

excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(fname)
wb.SaveAs(fname + "x", FileFormat = 56)

wb.Close()                                 
excel.Application.Quit()
quit()

Any help will be great.任何帮助都会很棒。

@echo off
setlocal
cd /d "%~dp0" || exit /b 1

for %%A in (*.zip) do (
    call :UnZipFile "%cd%\" "%%~fA"

    for %%B in (*.xls) do (
        echo python mypython.py --sourcefilepath "%cd%" --sourcefilename "%%~nxB"
        del "%%~B"
    )
)
exit /b

:UnZipFile <ExtractTo> <newzipfile>
if "%~dp0" == "" exit /b 1
set "vbs=%temp%\_.vbs"
if exist "%vbs%" del /f /q "%vbs%"

(
    echo Set fso = CreateObject("Scripting.FileSystemObject"^)
    echo If NOT fso.FolderExists("%~1"^) Then
    echo fso.CreateFolder("%~1"^)
    echo End If
    echo set objShell = CreateObject("Shell.Application"^)
    echo set FilesInZip=objShell.NameSpace("%~2"^).items
    echo objShell.NameSpace("%~1"^).CopyHere FilesInZip, 16
    echo Set fso = Nothing
    echo Set objShell = Nothing
) > "%vbs%"

cscript //nologo "%vbs%"
if exist "%vbs%" del /f /q "%vbs%"

Just some minor fixes to special characters needing escaping in the echo commands.只是对需要在echo命令中转义的特殊字符进行了一些小修正。 Replaced goto continue with exit /b 1 .goto continue替换为exit /b 1 Added simple for loop to get all zip filenames.添加了简单的for循环以获取所有 zip 文件名。

It will get xls files in the current directory and delete the xls files once the python script has done the SaveAs task.它将在当前目录中获取 xls 文件,并在 python 脚本完成 SaveAs 任务后删除 xls 文件。

Remove echo in front of python command if checked as OK.如果检查为 OK,则删除 python 命令前面的echo


Or try this python code which does the looping, unzipping, and xls to xlsx.或者试试这个 python 代码,它执行循环、解压缩和 xls 到 xlsx。

import win32com.client as win32
import argparse
import glob
import os
import zipfile

def xls_to_xlsx(filename, filepath=None):
    if not filepath:
        filepath = os.getcwd()

    fname = os.path.join(filepath, filename)

    excel = win32.gencache.EnsureDispatch('Excel.Application')
    wb = excel.Workbooks.Open(fname)
    wb.SaveAs(fname + "x", FileFormat = 56)

    wb.Close()
    excel.Application.Quit()

if __name__ == '__main__':
    for zip_file in glob.iglob('*.zip'):
        with zipfile.ZipFile(zip_file) as r:
            r.extractall()

        for xls_file in glob.iglob('*.xls'):
            xls_to_xlsx(xls_file)
            os.remove(xls_file)

It does not set current working directory which Task Scheduler can set it, or you can add it into the python script to set it.它不设置Task Scheduler可以设置的当前工作目录,或者您可以将其添加到python脚本中进行设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM