【发布时间】:2019-03-25 14:23:55
【问题描述】:
您好,我目前正在开发一个必须提取一些 .tar 文件的工具。
它在大多数情况下都很好用,但我有一个问题:
某些 .tar 和 .zip 文件的名称包含“非法”字符(f.ex“:”)。 这个程序必须在 windows 机器上运行,所以我必须处理这个。
如果提取的输出中包含“:”或其他非法 Windows 字符,我是否可以更改某些文件的名称。
我目前的实现:
def read_zip(filepath, extractpath):
with zipfile.ZipFile(filepath, 'r') as zfile:
contains_bad_char = False
for finfo in zfile.infolist():
if ":" in finfo.filename:
contains_bad_char = True
if not contains_bad_char:
zfile.extractall(path=extractpath)
def read_tar(filepath, extractpath):
with tarfile.open(filepath, "r:gz") as tar:
contains_bad_char = False
for member in tar.getmembers():
if ":" in member.name:
contains_bad_char = True
if not contains_bad_char:
tar.extractall(path=extractpath)
所以目前我只是忽略了这些输出,这并不理想。
为了更好地描述我的要求,我可以提供一个小例子:
file_with_files.tar -> small_file_1.txt
-> small_file_2.txt
-> annoying:file_1.txt
-> annoying:file_1.txt
应该提取到
file_with_files -> small_file_1.txt
-> small_file_2.txt
-> annoying_file_1.txt
-> annoying_file_1.txt
是迭代压缩文件中的每个文件对象并逐个提取的唯一解决方案,还是有更优雅的解决方案?
【问题讨论】:
-
您需要使用一个库,该库允许您提供一个回调函数,该函数将动态替换每个 ':' 为 '_'。例如,Zip-Ada 可以做到这一点,请参阅 Compose_func @unzip-ada.sf.net/za_html/unzip__ads.htm#85_8