[英]Why aren't file contents getting copied into my tarfile
这是一些用于将zipfile的内容复制到tarfile的代码。 稍后,我打算将复制限制为出现在作为进一步参数传入的列表中的文件,但是现在,我只是在尝试进行复制工作。
import zipfile, tempfile, shutil, tarfile, os
def gather_and_repackage_files(zip_file_path, target_file_path) :
with tarfile.open(target_file_path, "w") as tar:
with zipfile.ZipFile(zip_file_path) as zip_file:
for member in zip_file.namelist():
filename = os.path.basename(member)
# skip directories
if not filename:
continue
print "File: ", filename
# copy file (taken from zipfile's extract)
source = zip_file.open(member)
with tempfile.NamedTemporaryFile(delete=False) as temp:
print temp.name
shutil.copyfileobj(source, temp)
tar.add(temp.name, arcname=filename)
gather_and_repackage_files("./stuff.zip", "./tarfile.tar")
在运行此命令之前,目录的内容是“ testin.py”(上面的程序)和“ stuff.zip”。 “ stuff.zip”是一个zipfile,其中包含两个小文本文件a.txt和b.txt,每个文本文件包含大约15个字符。 显然,它也包含这些Mac备份,“ _ a.txt”和“ _b.txt”(尽管当我使用Archive Utility对其进行扩展时,即使使用“ ls -al”也不会出现)。
执行之后(Python 2.7.10),还有一个附加文件“ tarfile.tar”; 当我在Mac上使用“存档”实用程序打开此文件时,会看到以下内容:
drwx------ 6 jfh staff 204 Oct 29 16:51 .
drwxr-xr-x 7 jfh staff 238 Oct 29 16:51 ..
-rw------- 1 jfh staff 0 Oct 29 16:50 ._a.txt
-rw------- 1 jfh staff 0 Oct 29 16:50 ._b.txt
-rw------- 1 jfh staff 0 Oct 29 16:50 a.txt
-rw------- 1 jfh staff 0 Oct 29 16:50 b.txt
在执行过程中创建的临时文件实际上确实包含15个左右的愚蠢字符,但是tarfile中的字符长度为零。
所以我的问题是“为什么tar文件包含长度为0的a.txt和b.txt版本?”
临时文件可能尚未完全刷新。
您可以尝试:temp.flush()os.fsync()
但是当然最好不要首先创建临时文件。 您可以通过使用tar.addfile
而不是tar.add
来避免tar.add
。
您还需要设置所提供的tarinfo的大小。
注意:您还可以设置mtime来保留时间。
此修改应做到:
import zipfile
import tarfile
import os
def gather_and_repackage_files(zip_file_path, target_file_path) :
with tarfile.open(target_file_path, "w") as tar:
with zipfile.ZipFile(zip_file_path) as zip_file:
for info in zip_file.infolist():
filename = os.path.basename(info.filename)
# skip directories
if not filename:
continue
# copy file (taken from zipfile's extract)
with zip_file.open(info) as source:
tarinfo = tarfile.TarInfo(filename)
tarinfo.size = info.file_size
tar.addfile(tarinfo, source)
gather_and_repackage_files("./stuff.zip", "./tarfile.tar")
这是工作代码:
import zipfile, tempfile, shutil, tarfile, os
def gather_and_repackage_files(zip_file_path, target_file_path) :
with tarfile.open(target_file_path, "w") as tar:
with zipfile.ZipFile(zip_file_path) as zip_file:
for member in zip_file.namelist():
filename = os.path.basename(member)
# skip directories
if not filename:
continue
print "File: ", filename
print "Member: ", member
source = zip_file.open(member)
with tempfile.NamedTemporaryFile(delete=False) as temp:
print temp.name
shutil.copyfileobj(source, temp)
temp.close()
tar.add(temp.name, arcname=filename)
秘诀是在“ temp.close()”中,即结束前一行。 事实证明,您无法将打开的文件添加到tar归档文件中(尽管文档中似乎没有提及)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.