我需要 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文件夹中的文件时,我看不到这些文件。你知道吗
请注意,您从未实际调用过
searchfile()
,即使调用过,如果abc.zip
不匹配,也不会定义found
。你知道吗如果您想在一个单独的函数中进行文件搜索(这是一个好主意),最好让它返回一个成功/失败布尔值,而不是依赖于全局变量。你知道吗
因此,您可能需要这样的内容:(注意:代码未测试)
唯一定义
found
的地方是在if
块中,因此如果找不到abc.zip
,则found
将是未定义的。而且,即使找到了abc.zip
,并且定义了found
,它也被定义为searchfile()
的局部变量,您的主作用域将无法访问它。您应该在主作用域中将其初始化为全局变量,并在searchfile()
中将其声明为全局变量,以便对它的修改可以反映在主作用域中:但是使用全局变量实际上是没有必要的,因为您可以简单地从
searchfile()
返回found
作为返回值:相关问题 更多 >
编程相关推荐