我为压缩文件编写了一个函数,如下所示:
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'。
我做错了什么?先谢谢!
答案 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
的内容。