【问题标题】:Python error extracting zip filePython 提取 zip 文件时出错
【发布时间】:2017-11-29 20:47:30
【问题描述】:

我只知道如何为 GIS 目的编写 python。使用 arcpy 和地理处理工具的代码还有更多内容......这只是我坚持的开始部分,它是为了尝试准备好数据,这样我就可以将压缩文件夹中的 shapefile 用于我的其余部分脚本

我正在尝试提示用户输入要搜索的目录。为了使用这个脚本,它将搜索一个压缩的 zip 文件,然后将所有文件解压缩到同一个目录。

import zipfile, os


# ask what directory to search in 
mypath = input("Enter .zip folder path: ")
extension = ".zip"

os.chdir(mypath) # change directory from working dir to dir with files

for item in os.listdir(mypath):
    if item.endswith(extension):
        filename = os.path.abspath(item)
        zip_ref = zipfile.ZipFile(filename)
        zip_ref.extractall(mypath)
        zip_ref.close()

尝试了你们的建议,但仍然存在以下问题:

import zipfile, os

mypath = input("Enter folder: ")


if os.path.isdir(mypath):
    for dirpath, dirname, filenames in os.listdir(mypath):
        for file in filenames:
            if file.endswith(".zip"):
                print(os.path.abspath(file))
                with zipfile.ZipFile(os.path.abspath(file)) as z:
                    z.extractall(mypath)

else:
    print("Directory does not exist.")

【问题讨论】:

  • “停止工作”是什么意思?有错误吗? print(file_name) 是否显示文件的正确路径?看起来您的代码在 else: 之后没有正确缩进。
  • 我的程序中的缩进是正确的,当我在这里发帖时它被移到了左边。我不擅长解释事情,对不起。它将完全运行,我得到“进程以退出代码 0 完成”(我正在使用 PyCharm)......但它实际上并没有解压缩我为目录输入的文件夹。我不知道为什么,我只是测试了一些打印语句,这就是我发现它在“if item.endswith(".zip")”行之后的某个地方
  • 我不确定您是如何循环访问代码中的文件的。使用 os.listdiros.walk 获取文件夹内的文件。
  • 我不明白如何使用 os.这一切都让我更加困惑
  • @hawkia os 是一个 python 模块,它提供了一种使用操作系统相关功能的可移植方式。 os.listdir 返回一个列表,其中包含路径给定的目录中条目的名称检查一些答案以了解它是如何工作的

标签: python zip gis unzip arcpy


【解决方案1】:

我不确定arcpy 的使用。不过……

要遍历目录中的条目,请使用os.listdir

for entry_name in os.listdir(directory_path): 
    # ...

在循环中,entry_name 将是directory_path 目录中项目的名称。

检查是否以“.zip”结尾时,请记住比较区分大小写。在使用str.endswith 时,您可以使用str.lower 有效地忽略大小写:

if entry_name.lower().endswith('.zip'):
        # ...

要获取条目的完整路径(在本例中为您的 .zip),请使用 os.path.join

entry_path = os.path.join(directory_path, entry_name)

将此完整路径传递给zipfile.ZipFile

【讨论】:

    【解决方案2】:

    如果位置无效,您的第一个 if 块将否定 else 块。我会完全删除“else”运算符。如果你保留它,if-check 会有效地杀死程序。 "if folderExist" 足以替代 else。

    import arcpy, zipfile, os
    
    
    # ask what directory to search in 
    folder = input("Where is the directory? ")
    # set workspace as variable so can change location
    arcpy.env.workspace = folder
    
    # check if invalid entry - if bad, ask to input different location
    if len(folder) == 0:
        print("Invalid location.")
        new_folder = input("Try another directory?")
        new_folder = folder
        # does the above replace old location and re set as directory location?
    
    
    
    # check to see if folder exists
    folderExist = arcpy.Exists(folder)
    if folderExist:
        # loop through files in directory
            for item in folder:
            # check for .zip extension
                if item.endswith(".zip"):
                     file_name = os.path.abspath(item) # get full path of files
                     print(file_name)
                     zip_ref = zipfile.ZipFile(file_name) # create zipfile object
                     zip_ref.extractall(folder) # extract all to directory
                     zip_ref.close() # close file
    

    如果您可以不使用原始代码,这可能会更简洁:

    import zipfile, os
    from tkinter import filedialog as fd
    
    # ask what directory to search in 
    folder = fd.askdirectory(title="Where is the directory?")
    
    # loop through files in directory
    for item in os.listdir(folder):
         # check for .zip extension
         if zipfile.is_zipfile(item):
             file_name = os.path.abspath(item) # get full path of files
             # could string combine to ensure path
             # file_name = folder + "/" + item
             print(file_name)
    
             zip_ref = zipfile.ZipFile(file_name) # create zipfile object
             zip_ref.extractall(folder) # extract all to directory
             zip_ref.close() # close file
    

    【讨论】:

    • 我尝试进行您建议的更改,但仍然没有提取文件。我正在使用其他人的帖子来弄清楚提取过程,所以我不知道为什么它仍然无法工作
    • 如果您可以验证问题不是源于 arcpy(在文件目录中设置环境似乎很奇怪,特别是如果您只是尝试提取 zip 文件),那么您应该检查一下如果 file_name 确实返回了您感兴趣的 zip 文件。
    【解决方案3】:

    [更新]

    我可以用下面的代码解决这个问题

    import os
    import zipfile
    
    mypath = raw_input('Enter Folder: ')
    
    if os.path.isdir(mypath):
        for file in os.listdir(mypath):
            if file.endswith('.zip'):
                with zipfile.ZipFile(os.path.join(mypath, file)) as z:
                    z.extractall(mypath)
    else:
        print('Directory does not exist')
    

    【讨论】:

    • 请注意os.walk 覆盖整个目录树(使用os.listdir),而os.listdir 仅覆盖目录。
    • 当我尝试这个时,它说“for dirpath, dirnames, filenames in os.walk(mypath):”有一个错误,说有太多变量需要解压
    • @hawkia 这不应该发生,它在我的身上运行良好。 os.walk 返回 3 个元组。你可以粘贴你试过的代码吗?
    • @DevUberoi 我不确定如何将代码正确添加到评论中,因此我将其添加到了原始帖子的末尾。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多