【问题标题】:How do I delete a (g)zip file in Windows via Python? (File generated in LabVIEW.)如何通过 Python 在 Windows 中删除 (g)zip 文件? (在 LabVIEW 中生成的文件。)
【发布时间】:2018-07-31 16:25:25
【问题描述】:

我有一些 zip 文件需要在 Python 3 中以编程方式删除。我根本不需要先打开它们:我可以仅根据文件名确定是否要删除它们。在为这个问题扫描 SO 时,我注意到以下不令人满意的问题(不令人满意,例如,我尝试了他们所有的方法都没有成功):

  1. Removing path from a zip file using python
  2. Python zipfile doesn't release zip file
  3. Unable to remove zipped file after unzipping
  4. os.remove() in windows gives "[Error 32] being used by another process"

特别是,调用close() 方法或在with 子句中打开文件不会释放任何Windows 锁。 我能做到的最简单的MWE梦想是这样的:

import os
file_path = r'C:\Users\akeister\Desktop\Tatsuro 1.2.0.zip'
os.remove(file_path)

这段代码产生:

PermissionError: [WinError 32] The process cannot access the file because it 
is being used by another process: 'C:\\Users\\akeister\\Desktop\\Tatsuro 
1.2.0.zip'

如果我尝试,我会得到同样的错误

import os
file_path = r'C:\Users\akeister\Desktop\Tatsuro 1.2.0.zip'
with open(file_path) as f:
    f.close()
os.remove(file_path)

import gzip
import os
file_path = r'C:\Users\akeister\Desktop\Tatsuro 1.2.0.zip'
with gzip.GzipFile(file_path) as f:
    f.close()
os.remove(file_path)

import zipfile
import os
zipped_file = r'C:\Users\akeister\Desktop\Tatsuro 1.2.0.zip'
with zipfile.ZipFile(zipped_file) as zip_file:
    for member in zip_file.namelist():
        filename = os.path.basename(member)
        if not filename:
            continue
        source = zip_file.open(member)
os.remove(zipped_file)

没有打开桌面的命令提示符,也没有打开桌面的 Windows 资源管理器窗口。

我怀疑我的部分问题是文件可能是 gzip 文件,而不是常规的 zip 文件。我不完全确定它们是什么。我使用内置的 zip 函数在 LabVIEW 2015 中生成了 zip 文件(至少,它们具有 .zip 扩展名)。从 LabVIEW 文档中并不清楚 zip 函数使用哪种压缩。

我的问题的解决方案是什么?提前感谢您的宝贵时间!

【问题讨论】:

  • 在LabVIEW中创建ZIP文件后是否关闭它? zone.ni.com/reference/en-XX/help/371361M-01/glang/…
  • @Lithis:是的,我愿意。我认为发布的答案是正确的。
  • @AdrianKeister 你能贴一张创建 .zip 文件的 LV 代码的图片吗?看看里面是否有什么特别的东西可以让 LV 保持文件打开会很有用。

标签: windows python-3.x zip gzip labview


【解决方案1】:

我相信解决方案是解决您得到的错误的根本原因:

PermissionError: [WinError 32] The process cannot access the file because it 
is being used by another process: 'C:\\Users\\akeister\\Desktop\\Tatsuro 
1.2.0.zip'

这似乎不是一个 Python 问题,而是一个 Windows 和/或 LabVIEW 问题。

如果另一个进程锁定了文件,则无法删除文件是正常行为。因此,必须释放锁(LabVIEW 似乎仍在持有)。

我建议识别 LabVIEW PID 并停止或重新启动 LABVIEW。

您可以尝试合并https://null-byte.wonderhowto.com/forum/kill-processes-windows-using-python-0160688/https://github.com/cklutz/LockCheck(一种基于Windows 的文件锁定程序)。

如果您可以将其中任何一个合并到您的 Python 程序中以关闭或重新启动锁定过程,那么 zip 文件应该是可移除的。

【讨论】:

  • 愚蠢的我。不敢相信我没想到!我想我现在走在正确的轨道上。非常感谢!
【解决方案2】:

为了完整起见,我将发布有效的代码(在完全关闭 LabVIEW 之后):

import shutil
import os
import tkinter as tk


""" ----------------- Get delete_zip_files variable. --------------- """


delete_zip_files = False

root= tk.Tk() # create window

def delete_button():
    global delete_zip_files

    delete_zip_files = True
    root.destroy()

def leave_button():
    global delete_zip_files

    delete_zip_files = False
    root.destroy()


del_button = tk.Button(root, text='Delete Zip Files',
                   command=delete_button)
del_button.pack()  

lv_button = tk.Button(root, text='Leave Zip Files',
                  command=leave_button)
lv_button.pack()                     

root.mainloop()

print(str(delete_zip_files))


""" ----------------- List files in user's desktop. ---------------- """


# Desktop path is os.path.expanduser("~/Desktop")
# List contents of a directory: os.listdir('directory here')
desktop_path = os.path.expanduser("~/Desktop")

for filename in os.listdir(desktop_path):
    if filename.startswith('Tatsuro') or \
            filename.startswith('TestScript'):
        # Get full path to file.
        file_path = os.path.join(desktop_path, filename)

        if filename.endswith('2015'):
            # It's a folder. Empty the folder, then delete the folder:
            shutil.rmtree(file_path)

        if filename.endswith('.zip'):
            # Get desired folder name. 
            target_folder_name = filename.split('.zip')[0]
            target_folder_path = os.path.join(desktop_path, 
                                              target_folder_name)

            # Now we process. Unzip and delete.
            shutil.unpack_archive(file_path, target_folder_path)

            if delete_zip_files:

                # Now we delete if the user chose that.
                os.remove(file_path)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-07
    • 2016-06-16
    • 1970-01-01
    • 2022-01-25
    • 2022-11-15
    • 1970-01-01
    相关资源
    最近更新 更多