Read bin files python

Чтение бинарных файлов с помощью Python

Файл, содержащий бинарные данные, называется двоичным (бинарным) файлом. Любые форматированные и неформатированные бинарные данные хранятся в бинарных файлах, нечитабельных для человека и использующихся компьютером напрямую.

Когда бинарный файл требуется просмотреть или переместить, содержимое файла переводится в формат, понятный человеку. Бинарный файл имеет расширение .bin. Прочитать его можно с помощью встроенной функции или модуля. В этом уроке мы разберём различные способы чтения бинарных файлов с помощью Python.

Подготовка

Перед тем, как начать урок, желательно создать один или несколько бинарных файлов, чтобы воспользоваться скриптом из примера. Ниже представлены два скрипта на Python, которые создадут два бинарника. Файл binary1.py создаёт string.bin, содержащий строковые данные, а binary2.py – number_list.bin со списком из числовых данных.

Binary1.py

# Создаём бинарный файл file_handler = open("string.bin", "wb") # Добавляем две строки в бинарный файл file_handler.write(b"Welcome to LinuxHint.\nLearn Python Programming.") # Закрываем чтение file_handler.close()

Binary2.py

# Создаём бинарный файл file=open("number_list.bin","wb") # Объявляем список с числовыми данными numbers=[10,30,45,60,70,85,99] # Конвертируем список в массив barray=bytearray(numbers) # Записываем массив в файл file.write(barray) file.close()

Считываем бинарный файл со строковыми данными в массив байтов

В Python существует множество способов прочитать бинарный файл. Можно прочитать определённое количество байтов или весь файл сразу.

В приведенном ниже коде функция open() открывает для чтения string.bin, а функция read() на каждой итерации цикла while считывает по 7 символов в файле и выводит их. Далее мы используем функцию read() еще раз, но уже без аргументов — для считывания всего файла. После считывания содержимое выводится на экран.

# Открываем бинарный файл на чтение file_handler = open("string.bin", "rb") # Читаем первые 7 байтов из файла data_byte = file_handler.read(7) print("Print three characters in each iteration:") # Проходим по циклу, чтобы считать оставшуюся часть файла while data_byte: print(data_byte) data_byte = file_handler.read(7) # Записываем всё содержимое файла в байтовую строку with open('string.bin', 'rb') as fh: content = fh.read() print("Print the full content of the binary file:") print(content)

Результат

После выполнения скрипта мы получим следующий результат.

Считываем бинарный файл со строковыми данными в массив

Следующий скрипт поможет нам прочитать бинарник number_list.bin, созданный нами ранее.

# Открываем на чтение бинарный файл file = open("number_list.bin", "rb") # Считываем в список первые 5 элементов number = list(file.read(5)) # Выводим список print(number) # Закрываем файл file.close()

Бинарный файл содержит список с числовыми данными. Как и в предыдущем примере, функция open() открывает файл и читает из него данные. Затем из бинарника читаются первые 5 чисел и перед выводом объединяются в список.

Результат

После выполнения скрипта мы получим следующий результат. Бинарный файл содержит 7 чисел, первые 5 вывелись на консоль.

Читайте также:  Php docs default value

Читаем бинарный файл с помощью NumPy

В этой части мы поговорим о том, как создать бинарный файл и прочитать его с помощью массивов NumPy. Перед началом работы необходимо установить модуль NumPy командой в терминале или через ваш редактор Python, в котором вы будете писать программу.

Функция tofile() создаёт текстовый или бинарный файл, а fromfile() считывает данные из файла и создаёт массив.

Синтаксис tofile()

ndarray.tofile(file, sep='', format='%s')

Первый аргумент обязательный – он принимает имя файла, путь или строку. Файл создастся, только если будет указан первый аргумент. Второй аргумент – необязательный, он используется для разделения элементов массива. Третий аргумент также необязателен, он отвечает за форматированный вывод содержимого файла.

Синтаксис fromfile()

numpy.fromfile(file, dtype=float, count=- 1, sep='', offset=0, *, like=None)

Первый аргумент обязательный – он принимает имя файла, путь или строку. Содержимое файла будет прочитано, только если вы укажете имя файла. dtype определяет тип данных в возвращаемом массиве. Count задаёт число элементов массива. Sep – для разделения элементов текста или массива. Offset определяет позицию в файле, с которой начинается считывание. Последний аргумент нужен, чтобы создать массив, не являющийся массивом NumPy.

Напишем следующий код, чтобы создать бинарный файл с помощью массива NumPy, прочитать его и вывести содержимое.

# Импортируем NumPy import numpy as np # Объявляем массив numpy nparray = np.array([34, 89, 30, 45, 90, 11]) # Создаём бинарный файл из numpy-массива nparray.tofile("list.bin") # Выведем данные из бинарного файла print(np.fromfile("list.bin", dtype=np.int64))

Результат

После выполнения скрипта мы увидим следующий результат.

Заключение

Мы рассмотрели 3 разных способа чтения бинарных файлов. В первом примере мы получили содержимое файла в виде массива байтов, во втором и третьем – в виде списка.

Источник

How to Read Binary Files in Python

The file that contains the binary data is called a binary file. Any formatted or unformatted binary data is stored in a binary file, and this file is not human-readable and is used by the computer directly. When a binary file is required to read or transfer from one location to another location, the file’s content is converted or encoded into a human-readable format. The extension of the binary file is .bin. The content of the binary file can be read by using a built-in function or module. Different ways to read binary files in Python have been shown in this tutorial.

Pre-requisite:

Before checking the examples of this tutorial, it is better to create one or more binary files to use in the example script. The script of two python files has given below to create two binary files. The binary1.py will create a binary file named string.bin that will contain string data, and the binary2.py will create a binary file named number_list.bin that will contain a list of numeric data.

Читайте также:  Php проверка строки чтобы только кириллица

Binary1.py

# Open a file handler to create a binary file

file_handler = open ( «string.bin» , «wb» )

# Add two lines of text in the binary file

file_handler. write ( b «Welcome to LinuxHint. \n Learn Python Programming.» )

Binary2.py

# Open a file handler to create a binary file

file = open ( «number_list.bin» , «wb» )

# Declare a list of numeric values

numbers = [ 10 , 30 , 45 , 60 , 70 , 85 , 99 ]

# Convert the list to array

barray = bytearray ( numbers )

# Write array into the file

Example-1: Read the binary file of string data into the byte array

Many ways exist in Python to read the binary file. You can read the particular number of bytes or the full content of the binary file at a time. Create a python file with the following script. The open() function has used to open the string.bin for reading. The read() function has been used to read 7 characters from the file in each iteration of while loop and print. Next, the read() function has been used without any argument to read the full content of the binary file that will be printed later.

# Open the binary file for reading

file_handler = open ( «string.bin» , «rb» )

# Read the first three bytes from the binary file

data_byte = file_handler. read ( 7 )

print ( «Print three characters in each iteration:» )

# Iterate the loop to read the remaining part of the file

data_byte = file_handler. read ( 7 )

# Read the entire file as a single byte string

with open ( ‘string.bin’ , ‘rb’ ) as fh:

print ( «Print the full content of the binary file:» )

Output:

The following output will appear after executing the above script.

Example-2: Read the binary file of string data into the array

Create a python file with the following script to read a binary file named number_list.bin created previously. This binary file contains a list of numeric data. Like the previous example, the open() function has used open the binary file for reading in the script. Next, the first 5 numbers will be read from the binary file and converted into a list before printing.

# Open the binary file for reading

file = open ( «number_list.bin» , «rb» )

# Read the first five numbers into a list

number = list ( file . read ( 5 ) )

Output:

The following output will appear after executing the above script. The binary file contains 7 numbers, and the first five numbers have printed in the output.

Читайте также:  Как получить адресную строку python

Example-3: Read binary file using NumPy

The ways to create the binary file using the NumPy array and read the content of the binary file using into a list by using the NumPy module have shown in this part of the tutorial. Before checking the script given below, you have to install the NumPy module by executing the command from the terminal or installing the NumPy package in the Python editor, where the script will be executed. The tofile() function is used to create a text or binary file, and the fromfile() function is used to create an array by reading a text or binary file.

Syntax of tofile():

The first argument is mandatory and takes the filename or string or path as a value. The file will be created if a filename is provided in this argument. The second argument is optional that is used to separate the array elements. The third argument is optional also and used for formatting the output of the text file.

Syntax of fomfile():

The first argument is mandatory and takes the filename or string or path as a value. The content of the file will be read if a filename will be provided in this argument. The dtype defines the data type of the returned array. The count is used to count the number of items. The purpose of the sep is to separate the text or array items. The offset is used to define the current position of the file. The last argument is used to create an array object that not a NumPy array.

Create a python file with the following script to create a binary file using NumPy array and read and print the content of the binary file.

nparray = np. array ( [ 34 , 89 , 30 , 45 , 90 , 11 ] )

# Create binary file from numpy array

# Print data from the binary file

print ( np. fromfile ( «list.bin» , dtype = np. int64 ) )

Output:

The following output will appear after executing the above script.

Conclusion:

Three different ways to read the binary file have been shown in this tutorial by using simple examples. The first example returned the content of the binary file as a byte array. The second example returned the content of the binary file as a list. The last example also returned the content of the binary file as a list.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Оцените статью