0

我已经在论坛中搜索了这种错误,但找不到任何错误,所以我正在为它创建新线程。我正在使用以下 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' object has no attribute '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 命令提取文件。

4

2 回答 2

3

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

于 2013-07-31T15:44:02.293 回答
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对象)作为第一个参数。

于 2013-07-31T15:45:08.980 回答