首先来看一张图片:
1.遍历文件夹下的所有文件(为了方便,假设只有一层文件夹)
代码语言:javascript复制for parent, dir_names, file_names in os.walk(person_dir):
for file_name in file_names:
print file_name
解压tar,tar.gz
代码语言:javascript复制#解压
import tarfile
import os
def untar(fname, dirs):
t = tarfile.open(fname)
t.extractall(path = dirs)
if __name__ == "__main__":
untar("del.tar.gz", ".")
压缩
代码语言:javascript复制import tarfile
import os
def tar(fname):
t = tarfile.open(fname ".tar.gz", "w:gz")
for root, dir, files in os.walk(fname):
print root, dir, files
for file in files:
fullpath = os.path.join(root, file)
t.add(fullpath)
t.close()
if __name__ == "__main__":
tar("del")
结果
代码语言:javascript复制del ['del2'] ['del2.txt']
deldel2 [] ['del3.txt']