如何使用python查找zip文件,解压缩,在其中查找特定文件?



我需要 1( 在特定目录位置查找压缩文件 2(如果存在,则解压缩 3(从其内容中找到一个特定的文件并将其移动到其他目录。

def searchfile():
for file in os.listdir('/user/adam/datafiles'):
    if fnmatch.fnmatch(file, 'abc.zip'):
        return True
return False

如果搜索文件((:

print('File exists')

还:

print('File not found')

def file_extract((:

    os.chdir('/user/adam/datafiles')
    file_name = 'abc.zip'
    destn = '/user/adam/extracted_files'
    zip_archive = ZipFile (file_name)
    zip_archive.extract('class.xlsx',destn)
    print("Extracted the file")
    zip_archive.close()

search_file

file_extract

当我执行上述脚本时,它没有显示编译时问题或运行时问题,但它仅适用于第一个函数。当我检查extracte_files文件夹中的文件时,我看不到这些文件。

请注意,您从未真正调用过searchfile(),即使您调用了,如果不匹配abc.zipfound仍然不会被定义。

如果你想在一个单独的函数中搜索文件(这是一个好主意(,你最好让它返回一个成功/失败布尔值,而不是依赖于全局变量。

所以你可能想要这样的东西:(注意:代码未测试(

import os
import fnmatch
import zipfile
def searchfile():
        for file in os.listdir('/user/adam/datafiles'):
                if fnmatch.fnmatch(file, 'abc.zip'):
                        return True  # <-- Note this
        return False  # <-- And this
if searchfile():  # <-- Now call the function and use its return value
        print('File exists')
else:
        print('File not found')

您定义found的唯一位置是在if块中,因此如果未找到abc.zip,则found将未定义。但此外,即使找到abc.zip并定义了found,它也被定义为要searchfile()的局部变量,并且您的主范围将无法访问它。您应该在主作用域中将其初始化为全局变量,并在searchfile()中将其声明为全局变量,以便对它的修改可以反映在主作用域中:

def searchfile():
    global found
    for file in os.listdir('/user/adam/datafiles'):
        if fnmatch.fnmatch(file, 'abc.zip'):
            found = True
found = False
searchfile()
if found:
    print('File exists')
else:
    print('File not found')

但是使用全局变量确实没有必要,因为您可以简单地从 searchfile() 返回 found 作为返回值:

def searchfile():
    for file in os.listdir('/user/adam/datafiles'):
        if fnmatch.fnmatch(file, 'abc.zip'):
            return True
    return False
if searchfile():
    print('File exists')
else:
    print('File not found')

最新更新