python'function'对象没有属性'GzipFile'

时间:2013-05-21 13:12:57

标签: python object attributes gzip gzipfile

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

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'对象没有属性'GzipFile'。

我做错了什么?先谢谢!

2 个答案:

答案 0 :(得分:6)

您已将您的函数gzip命名为gzip模块。现在,当你运行你的函数时,python会抓取函数本身(想想递归)而不是你所隐藏的gzip模块。有两种解决方案。 1)重命名函数:

def gzip_func():
    ...

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

import gzip as gzip_mod
...
def gzip():
    ...
    w_file = gzip_mod.GzipFile(filename + '.gz', 'w', 9)

答案 1 :(得分:1)

您使用gzip模块,但您的功能名称相同,因此会覆盖模块。
您应该重命名该函数或使用类似import gzip as gzip_module的内容。