How to tell if a file is gzip compressed?

前端 未结 6 1358
挽巷
挽巷 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条回答
  •  死守一世寂寞
    2021-01-03 20:07

    "Is there a cross-platform, usable from Python way to determine if a file is gzip compressed or not?"

    The accepted answer got me 90% of the way to the pretty reliable solution (test if first two bytes are 1f 8b), but did not show how to actually do this in Python. Here is one possible way:

    def is_gz_file(filepath):
        with open(filepath, 'rb') as test_f:
            return test_f.read(2) == b'\x1f\x8b'
    

提交回复
热议问题