Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read text files within a zip file?

So say I have a zip file named "files.zip" it contains "text1.txt":

words

and "text2.txt":

other words

How do I tell python to open and read the text1.txt file? I know that usually to open a text file outside of a zip file I would just do this:

file = open('text1.txt','r')
like image 559
ajkey94 Avatar asked Mar 07 '13 22:03

ajkey94


People also ask

How do you view the contents in a zipped file?

Also, you can use the zip command with the -sf option to view the contents of the . zip file. Additionally, you can view the list of files in the . zip archive using the unzip command with the -l option.

How do I extract text from a zip file?

To unzip a single file or folder, open the zipped folder, then drag the file or folder from the zipped folder to a new location. To unzip all the contents of the zipped folder, press and hold (or right-click) the folder, select Extract All, and then follow the instructions.

Can ZIP files be read?

Just like regular digital folders, you can easily open a ZIP file on almost any computer or operating system. But, unlike regular folders, you need more than just a simple double-click to use the files inside it. Here's how to open a ZIP file on a Windows PC, Mac, iPhone, and Android devices.


2 Answers

If you need to open a file inside a ZIP archive in text mode, e.g. to pass it to csv.reader, you can do so with io.TextIOWrapper:

import io
import zipfile

with zipfile.ZipFile("files.zip") as zf:
    with io.TextIOWrapper(zf.open("text1.txt"), encoding="utf-8") as f:
        ...
like image 78
iafisher Avatar answered Sep 18 '22 17:09

iafisher


You can use the zipfile module like so:

zip = zipfile.ZipFile('test.zip')
file = zip.read('text1.txt')

Don't forget to import zipfile module: import zipfile

like image 40
solusipse Avatar answered Sep 20 '22 17:09

solusipse