在 Python 中的 "TarFile Object" 中插入变量

Insert variables in a "TarFile Object" in Python

我想在 "TarFile Object" 中插入一些变量。什么是正确的方法?谢谢

import tarfile
import datetime
import time

today = datetime.date.today()
timetoday = time.strftime("%H:%M:%S")
print today, timetoday
print timetoday

dirname="notes"
dirnamefullpath='/var/log/something'


print today, timetoday, 'Creating archive:', dirname

tar = tarfile.open("/backups/files/sitebackup-pythontest-[today]-[timetoday]-[dirname].tar.gz", "w:gz")
for name in [dirnamefullpath]:
    tar.add(name)

这一行:

for name in [dirnamefullpath]:

…创建一个包含一个元素的列表,dirnamefullpath,然后遍历该元素。

如果您想要文件系统目录中名为 dirnamefullpath 的实际文件,您必须向计算机询问这些文件名,通常使用 listdir (if you just want direct children) or walk(如果您想要所有后代, 递归地)。

在这种情况下,因为 TarFile.add 知道如何递归到目录中,您可能只需要直接子目录。例如:

for name in os.listdir(dirnamefullpath):
    tar.add(name)