AttributeError:'TarFile'对象没有属性'endswith'

时间:2013-07-31 15:36:56

标签: python

我在论坛上搜索过这种错误,但找不到任何内容,所以我正在为它创建新的帖子。我正在使用下面的python脚本存档一年的文件。

import os, time, tarfile
path = "/home/appins/.scripts/test/"
now = time.time()
yearago = now - 60*60*24*665
tar_file = "nas_archive_"+time.strftime("%m-%d-%Y")+".tgz"
tar = tarfile.open(tar_file,"w:gz")
for root, subFolders, files in os.walk(path):
    for file in files:
        file = os.path.join(root,file)
        file = os.path.join(path, file)
        filecreation = os.path.getctime(file)
        if filecreation > yearago:
            tar.add(file)
            print file," is older that one year"
            os.remove(file)

它工作得很好,我可以通过查看其内容。现在,当我尝试恢复存档文件并获取错误AttributeError时:'TarFile'对象没有属性'endswith'。

我的恢复脚本很简单:

import os, tarfile
archive_file = "nas_archive_07-31-2013.tgz"
tar = tarfile.open("nas_archive_07-31-2013.tgz")
tar.extractall(tar)
tar.close()

当我运行此脚本时,我收到以下错误:

python restore_archive.py
Traceback (most recent call last):
  File "restore_archive.py", line 8, in ?
    tar.extractall(tar)
  File "/usr/lib64/python2.4/tarfile.py", line 1541, in extractall
    self.extract(tarinfo, path)
  File "/usr/lib64/python2.4/tarfile.py", line 1578, in extract
    self._extract_member(tarinfo, os.path.join(path, tarinfo.name))
  File "/usr/lib64/python2.4/posixpath.py", line 62, in join
    elif path == '' or path.endswith('/'):
AttributeError: 'TarFile' object has no attribute 'endswith'

我在提取方面有什么问题吗?我可以使用tar -xzvf命令提取文件。

2 个答案:

答案 0 :(得分:3)

extractall方法采用提取路径。我不确定你为什么要把它传递给tar文件对象;你应该能够保留路径参数,并将其默认为当前目录。

答案 1 :(得分:1)

In [96]: help(tarfile.TarFile.extractall)

Help on function extractall in module tarfile:

extractall(self, path='.', members=None)
    Extract all members from the archive to the current working
    directory and set owner, modification time and permissions on
    directories afterwards. `path' specifies a different directory
    to extract to. `members' is optional and must be a subset of the
    list returned by getmembers().
(END)

因此,extractall期望路径(str对象)作为第一个参数。