Python Forum
read a binary file to find its type
Thread Rating:
  • 1 Vote(s) - 2 Average
  • 1
  • 2
  • 3
  • 4
  • 5
read a binary file to find its type
#2
Often it's much more complicated to guess a file type related to the content. Many file formats do have magic number at the beginning. If you want to get the first 3 bytes, then just read the first 3 bytes:

with open('YourFile.ext', 'rb') as fd:
    file_head = fd.read(3)
file_head has now the first 3 bytes. You can make a predefined table for comparison.

If you want just use a library/wrapper for it, you should look for this modules:
file-magic # official
filemagic

More about Magic numbers.

There are different ways to detect if a given sub string (bytes) is in a string.
If you want to detect PNG, you need for example 8 bytes.

magic_numbers = {'png': bytes([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])}
max_read_size = max(len(m) for m in magic_numbers.values()) # get max size of magic numbers of the dict

with open('YourFile.png', 'rb') as fd:
    file_head = fd.read(max_read_size)

if file_head.startswith(magic_numbers['png']):
    print("It's a PNG File")
else:
    print("It's not a png file")
It's just an example how you can do it.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
read a binary file to find its type - by atux_null - Nov-22-2017, 12:35 PM
RE: read a binary file to find its type - by DeaD_EyE - Nov-22-2017, 01:53 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Using dictionary to find the most sent emails from a file siliusu 6 7,789 Apr-22-2021, 06:07 PM
Last Post: siliusu
  Can we store value in file if we open file in read mode? prasanthbab1234 3 2,676 Sep-26-2020, 12:10 PM
Last Post: ibreeden
  [split] how to read a specific row in CSV file ? laxmipython 2 9,043 May-22-2020, 12:19 PM
Last Post: Larz60+
  Read data from a CSV file in S3 bucket and store it in a dictionary in python Rupini 3 7,170 May-15-2020, 04:57 PM
Last Post: snippsat
  read from file mcgrim 16 6,444 May-14-2019, 10:31 AM
Last Post: mcgrim
  Read directly from excel file using python script dvldgs05 0 2,317 Oct-19-2018, 02:51 AM
Last Post: dvldgs05
  Read a data from text file (Notepad) Leonzxd 24 14,442 May-23-2018, 12:17 AM
Last Post: wavic
  Homework - Read from/Write to file (renamed from Help help help) Amitkafle 1 3,116 Jan-11-2018, 07:24 AM
Last Post: wavic
  Cannot read from text file aljonesy 5 3,724 Oct-05-2017, 05:56 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020