python-libarchive-c
目前使用python 2.7、3.4、3.5和3.6进行测试。
用于 libarchive
的Python接口。 它使用标准的模块动态加载和访问C库。
python-libarchive-c
可能无法与过时的libarchive版本(如MacOS中包含的版本)正常工作。
在这种情况下,可以安装最新版本的 libarchive
(例如,使用 brew
在MacOS上安装 libarchive
)。
sudo apt install python3-libarchive-c
import os
if os.path.exists("xx_test.tar.gz"): os.remove('xx_test.tar.gz')
with open('xx_text.txt', 'w') as fo:
fo.write('Hello')
!ls xx*
xx_111113.zip xx_hello2.txt xx_text.txt xx_hello.txt xx_new2.zip xx_your.tar xx_out: new
import libarchive
with libarchive.file_writer('xx_test.tar.gz', 'ustar', 'gzip') as archive:
archive.add_files('xx_text.txt')
--------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) Cell In[6], line 1 ----> 1 import libarchive 2 with libarchive.file_writer('xx_test.tar.gz', 'ustar', 'gzip') as archive: 3 archive.add_files('xx_text.txt') ModuleNotFoundError: No module named 'libarchive'
!ls xx*
xx_111113.zip xx_hello2.txt xx_text.txt xx_hello.txt xx_new2.zip xx_your.tar xx_out: new
if os.path.exists('xx_text.txt'): os.remove('xx_text.txt')
libarchive.extract_file('xx_test.tar.gz')
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[5], line 2 1 if os.path.exists('xx_text.txt'): os.remove('xx_text.txt') ----> 2 libarchive.extract_file('xx_test.tar.gz') NameError: name 'libarchive' is not defined
!ls xx*
with libarchive.file_reader('xx_test.tar.gz') as reader:
for e in reader:
# (The entry evaluates to a filename.)
# print("> %s" % (e))
print(e.name)
Python-libarchive-c
模块为 Python 提供了对 libarchive
库的访问接口,支持多种压缩格式(如 ZIP、TAR、RAR 等)的读写操作。
通过 libarchive
模块可创建、提取和检查归档文件,使用 file_reader
读取归档内容,
file_writer
创建新归档,memory_reader
和 memory_writer
处理内存中的数据流。
该模块支持流式处理大文件,并保留文件权限和元数据,适合需要跨平台压缩解压的场景。
安装时需确保系统已安装 libarchive
库(如 apt-get install libarchive-dev
),
然后通过 pip install libarchive-c
安装 Python 绑定,使用时注意异常处理和资源释放以确保稳定性。