How to tell if a file is gzip compressed?

前端 未结 6 1352
挽巷
挽巷 2021-01-03 19:21

I have a Python program which is going to take text files as input. However, some of these files may be gzip compressed.

Is there a cross-platform, usable from Py

6条回答
  •  萌比男神i
    2021-01-03 20:03

    As of python3.7, this works

    import gzip
    with gzip.open(input_file, 'r') as fh:
        try:
            fh.read(1)
        except OSError:
            print('input_file is not a valid gzip file by OSError')
    

    As of python3.8, this also works:

    import gzip
    with gzip.open(input_file, 'r') as fh:
        try:
            fh.read(1)
        except gzip.BadGzipFile:
            print('input_file is not a valid gzip file by BadGzipFile')
    

提交回复
热议问题