如何找到一个zip文件,解压它,找到一个特定的文件中使用python?

2024-09-23 10:29:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要 1) 在特定目录位置查找zipfile 2) 如果它存在,那么解压它 3) 从其内容中找到一个特定的文件并将其移动到其他目录。你知道吗

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

如果searchfile():

print('File exists')

其他:

print('File not found')

def文件\u 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()

搜索\u文件

文件\u提取

当我执行上述脚本时,它没有显示编译时问题或运行时问题,。但它只适用于第一个函数。当我检查extracte\u files文件夹中的文件时,我看不到这些文件。你知道吗


Tags: 文件目录returnosdefzipfileabc
2条回答

请注意,您从未实际调用过searchfile(),即使调用过,如果abc.zip不匹配,也不会定义found。你知道吗

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

因此,您可能需要这样的内容:(注意:代码未测试)

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')

相关问题 更多 >