python: read lines from compressed text files

前端 未结 4 648
长发绾君心
长发绾君心 2020-11-27 18:09

Is it easy to read a line from a gz-compressed text file using python without extracting the file completely? I have a text.gz file which is aroud 200mb. When I extract it,

4条回答
  •  执念已碎
    2020-11-27 18:36

    Using gzip.GzipFile:

    import gzip
    
    with gzip.open('input.gz','rt') as f:
        for line in f:
            print('got line', line)
    

    Note: gzip.open(filename, mode) is an alias for gzip.GzipFile(filename, mode). I prefer the former, as it looks similar to with open(...) as f: used for opening uncompressed files.

提交回复
热议问题