python“function”对象没有属性“GzipFile”

2024-04-24 15:54:33 发布

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

我为压缩文件编写了一个函数,如下所示:

def gzip(filename):
    '''Gzip the given file and then remove original file.'''
    r_file = open(filename, 'r')
    w_file = gzip.GzipFile(filename + '.gz', 'w', 9)
    w_file.write(r_file.read())
    w_file.flush()
    w_file.close()
    r_file.close()
    os.unlink(filename) 

但是,当我运行我的程序时,我得到了一个错误:

'function' object has no attribute 'GzipFile'.

我做错什么了?先谢谢你!在


Tags: andthe函数closedeffilenamegivenremove
2条回答

您已经将函数命名为gzip,它与gzip模块相同。现在,当您运行函数时,python获取函数本身(考虑递归),而不是您跟踪的gzip模块。有两种解决方案。1) 重命名函数:

def gzip_func():
    ...

2)导入时为模块提供不同的本地名称:

^{pr2}$

您使用gzip模块,但您的函数具有相同的名称,因此它会覆盖该模块。
要么重命名函数,要么使用import gzip as gzip_module之类的东西。在

相关问题 更多 >