简体   繁体   中英

Python read n line of a file with zipfile.ZipFile

I would like to know if it's possible to read the second line of each files contains in a zip file?

zf = zipfile.ZipFile(myzip.zip)
for f in zf.namelist():
   csv_f = zf.read(f)
   first_line = csv_f.split('\n', 2)[0] ...?

thanks for any help.

Yes. Like this:

with zipfile.ZipFile("myzip.zip") as z:
    for n in z.namelist():
        with z.open(n) as f:
            for i in range(2):
                second_line = next(f)

This will only read the first two lines without reading the whole file, based on the recommendation by @S3DEV. One could be more fancy about not writing the first line to a variable second_line , but since it is overwritten on the second pass, this doesn't seem to clever.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM