Python tarfile路径问题
存在问题
假设在目录test1/test2
下有两个文件a.txt
和b.txt
test1
|--test2
| |--a.txt
| |--b.txt
|--test3
|--test4
现在需要将其压缩至test1/test3
目录下
很容易得到
def tar_files(file_name, from_path, to_path):
tar_file = file_name + '.tar.gz'
if not os.path.exists(to_path):
os.makedirs(to_path)
tar = tarfile.open(os.path.join(to_path, tar_file), 'w:gz')
files = [os.path.join(from_path, item) for item in os.listdir(from_path) if os.path.isfile(os.path.join(from_path, item))]
# print(files)
for file in files:
tar.add(file)
tar.close()
def tar_extract(file_name, from_path, to_path):
tar = tarfile.open(os.path.join(from_path, file_name), 'r:gz')
if not os.path.exists(to_path):
os.makedirs(to_path)
for file in tar.getnames():
tar.extract(file, to_path)
tar.close()
压缩
tar_files('mytar', 'test1/test2', 'test1/test3')
然后将压缩文件解压至test1/test4
目录
tar_extract('mytar.tar.gz', 'test1/test3', 'test1/test4')
那么问题来了
原本以为test4
目录下直接是a.txt
和b.txt
文件
结果发现解压后的两个文件保留了原有目录路径
即,在test4
目录下解压成了test1/test2/a.txt
和test1/test2/b.txt
而不是单纯的两个文件
解决方案
经测试,这两个文件路径与代码中tar.add(file)
中的file
的文件路径是一致的
那么只需要确保file
中的路径只为文件,不包含其所在目录就行了
这时就需要os.chdir()
来切换工作目录
切换至需要压缩的文件的目录下
添加了一些功能
def tar_files(file_name, from_path, to_path, delete=False):
'''
打包压缩一个目录下的文件
file_name: 生成的tar文件名,不需要有.tar.gz
from_path: 将from_path目录下的文件打包压缩
to_path: 将tar文件放在to_path目录下
delete: 是否删除from_path下的文件,默认False
'''
tar_file = file_name + '.tar.gz'
if not os.path.exists(to_path):
os.makedirs(to_path)
tar = tarfile.open(os.path.join(to_path, tar_file), 'w:gz')
# 记录当前工作目录
cur_path = os.getcwd()
# 切换目录
os.chdir(from_path)
files = [item for item in os.listdir('.') if os.path.isfile(item)]
for file in files:
tar.add(file)
tar.close()
if delete:
for file in files:
os.remove(file)
# 切换回原来工作目录
os.chdir(cur_path)
def tar_extract(file_name, from_path, to_path, delete=False):
'''
将压缩文件中的文件提取出来
file_name: 对应压缩文件 XXX.tar.gz
from_path: 压缩文件所在目录
to_path: 将文件提取至to_path目录
delete: 是否删除该压缩文件,默认False
'''
tar = tarfile.open(os.path.join(from_path, file_name), 'r:gz')
if not os.path.exists(to_path):
os.makedirs(to_path)
for file in tar.getnames():
tar.extract(file, to_path)
tar.close()
if delete:
os.remove(os.path.join(from_path, file_name))