Reputation: 21
I'm trying to print() the contents of a .txt file (called helloWorld.txt) and this .txt file is inside a .7z folder.
The folder is called FolderWorld.7z
Here's what I've tried:
import py7zr
import io
archive_path = 'FolderWorld.7z'
mnf_file_path = 'helloWorld.txt'
with py7zr.SevenZipFile(archive_path, mode='r') as z:
with z.open(mnf_file_path, 'r') as mnf_file:
mnf_content = mnf_file.read().decode()
print(mnf_content)
but it says z has no attribute "open"
I tried creating then a temp directory to read the txt file, like that:
import py7zr
import tempfile
archive_path = 'FolderWorld.7z'
mnf_file_path = 'helloWorld.txt'
with py7zr.SevenZipFile(archive_path, mode='r') as z:
with tempfile.TemporaryDirectory() as tmp_dir:
z.extract(mnf_file_path, path=tmp_dir)
extracted_file_path = tmp_dir + '/' + mnf_file_path
with open(extracted_file_path, 'r') as mnf_file:
mnf_content = mnf_file.read()
print(mnf_content)
Still nothing (it says that path has too many attributes)
Could you please help me?
Upvotes: 0
Views: 534
Reputation: 253
You should use read() method of SevenZipFile object, which return a dict of BytesIO object of the target files.
import py7zr
import io
archive_path = 'FolderWorld.7z'
mnf_file_path = 'helloWorld.txt'
with py7zr.SevenZipFile(archive_path, mode='r') as z:
mnf_content = z.read([mnf_file_path])[mnf_file_path].read().decode()
print(mnf_content)
Upvotes: 0