Можно ли в Python создавать бинарные файлы? Конечно можно.
Для этого в Python есть следующие инструменты:
▫️ тип данных bytes и bytearray
▫️ открытие файла в режиме wb (write binary) или rb (read binary)
▫️ модуль struct
Про модуль struct поговорим в первую очередь.
Файл в формате JSON или Yaml внутри себя содержит разметку данных. Всегда можно определить где список начался а где закончился. Где записана строка а где словарь. То есть формат записи данных содержит в себе элементы разметки данных.
В binary-файле данные не имеют визуальной разметки. Это просто байты, записанные один за другим. Правила записи и чтения находятся вне файла.
Модуль struct как раз и помогает с организацией данных в таком файле с помощью определения форматов записи для разных частей файла.
Модуль struct преобразует Python-объекты в массив байт, готовый к записи в файл и имеющий определённый вид.
Для этого всегда следует указывать формат преобразования (или, как оно здесь называется - запаковки).
Формат нужен для того, чтобы выделить достаточное количество байт для записи конкретного типа объекта. В последствии с помощью того же формата будет производиться чтение.
При этом следует помнить что мы говорим о типах языка С а не Python.
Именно формат определяет, что записано в конкретном месте файла, число, строка или что-то еще.
Вот какие токены формата у нас есть.
Помимо этого, первым символом можно указать порядок байтов. На разных системах одни и те же типы данных могут записываться по-разному, поэтому желательно указать конкретный способ из доступных. Если этого не сделать, то используется символ '@', то есть нативный для текущей системы.
В строке формата мы пишем в каком порядке и какие типы собираемся преобразовать в байты.
Запакуем в байты простое число, токен "i".
>>> import struct
>>> struct.pack('=i', 10)
b'\n\x00\x00\x00'
Теперь несколько float, при этом нужно передавать элементы не массивом а последовательностью аргументов.
>>> struct.pack('=fff', 1.0, 2.5, 4.1)
b'\x00\x00\x80?\x00\x00 @33\x83@'
Вместо нескольких токенов можно просто указать нужное количество элементов перед одним токеном, результат будет тот же.
>>> struct.pack('=3f', 1.0, 2.5, 4.1)
b'\x00\x00\x80?\x00\x00 @33\x83@'
Теперь запакуем разные типы
>>> data = struct.pack('=fiQ', 1.0, 4, 100500)
я запаковал типы float, int и unsigned long long (очень большой int, на 8 байт)
b'\x00\x00\x80?\x04\x00\x00...'
Распаковка происходит аналогично, но нужно указать тот же формат, который использовался при запаковке. Результат возвращается всегда в виде кортежа.
>>> struct.unpack('=fiQ', data)
(1.0, 4, 100500)
Как видите, ничего страшного!
#lib#basic
🇧🇷#Brazil: The 6th Military Police Battalion reportedly seized an iconic Luger Parabellum pistol, along with a radio, during an operation in the Rua Ernesto de Souza area of Rio de Janeiro.
According to police reports, the equipment was abandoned after a suspect fled the scene.
Rio de Janeiro, #Brazil🇧🇷
Markan's stadium is one of the most famous football symbols in the world.
The construction of the Marakan, the largest football stadium in the world, which received its name according to the name of a small river flowing nearby, began in 1948, in preparation for the 1950 World Cup.
In the days of matches, you can come before the start of the game to inspect all the attractions of the stadium. A tour of the stadium begins right from the entrance. The one who enters is in the famous “Hall of Glory”, where in the literal sense they left their mark (footprints) 91 best football player in the world.
🇧🇷#Brazil: A Comando Classe A (CCA) gang member brandishes what looks like an FGC-9 3D-printed "Stingray" variant on camera, threatening rival gang members in the Marabá area of southeastern Pará.
The incident comes after the alliance between CCA and the Primeiro Comando da Capital (PCC) collapsed in the state of Pará.
(via @submundooriginal)
🇧🇷#Brazil: The Civil Police of Rio Grande do Sul conducted a raid last Friday on a house in Novo Hamburgo, discovering a makeshift workshop for manufacturing FGC-9 submachine guns using 3D printers.
During the investigation, two men were caught red-handed while carrying an FGC-9 while posing as a ride-share driver and a passenger. The objective of the "trip" was to deliver the weapon to members of armed gangs in the metropolitan region of Porto Alegre.
After police teams located the manufacturing site of the 3D-printed weapons, a couple was arrested. At the scene, seven completed FGC-9s were seized, as well as several magazines and equipment used in the production of the weapons. The suspects demonstrated "advanced" technical knowledge in the manufacturing process, according to police.
(via terra.com.br & pc.rs.gov.br)
A hidden gem: Praia de Itaporoca, Brazil 🌴
This secluded paradise among the tranquil waters of Trancoso offers the perfect retreat for those seeking serenity and untamed natural beauty. 🌊
✨
#Brazil | @voyage
Brazil🌴
In the heart of Brazil, along the magical Atlantic coast, lies Lençóis Maranhenses National Park. This northern marvel in Maranhão, nestled between São José Bay and the Fomi River estuary, is a paradise for nature lovers. 🏝️
✨
#Brazil | @voyage
Brazil🇧🇷
Sucuri River - one of the clearest rivers in the world. The water here is so transparent that it's almost invisible. It creates the feeling that the fish are swimming in open air. The riverbanks covered in lush greenery are quite picturesque. 🌊🐟
The length of the river is 1800 meters.
The river is highly popular among divers and snorkeling enthusiasts. 🤿
#Brazil
@voyage
Brazil🇧🇷
Flying over the Lençóis Maranhenses Desert!
The desert covers an area of approximately 1,450 square kilometers, entirely covered with sand dunes that exceed 40 meters in height. And all of this is flooded with water, as the Amazon Basin is relatively close by.
Every year at a certain time, heavy rains pour here in such quantities that the soil cannot absorb them in time, they collect between the dunes and create a landscape of extraordinary beauty. 🏜️🌧️🌅
#Brazil
@voyage
Brazil🇧🇷
Aguia-do-Diabo, a rock formation standing at 2050 meters in height, is located in the city of Guapimirim, state of Rio de Janeiro. The peak is within the boundaries of the Serra dos Orgaos National Park. 😶🌫️
Aguia-do-Diabo is considered one of the most beautiful places for climbing in the world. 🌄
#Brazil
@voyage
Telegram Diam-diam Mengubah Ketentuan Penggunaan di Brasil
Setelah apa yang terjadi pada 18 Maret 2022, Telegram mengubah Ketentuan Penggunaannya, mengikuti keputusan Menteri Alexandre de Moraes. Menurut pengguna di grup kami, saat mengakses halaman Privasi Kebijakan dan Ketentuan Penggunaan di situs web Telegram di Brasil, mungkin untuk memperhatikan bahwa sekarang ada istilah keempat di yang mengatakan bahwa dilarang untuk berpartisipasi dalam kegiatan ilegal dengan terorisme dan pelecehan anak.
Selain itu, Telegram sekarang dapat meneruskan data IP Anda jika "Telegram menerima perintah pengadilan dari negara demokratis seperti Brasil terkait penggunaan platform publik Telegram untuk aktivitas yang dilarang oleh Ketentuan Penggunaan"
Bot untuk informasi GDPR juga dibuat, @lgpdbot, berbeda dari @gdprbot untuk Uni Eropa.
Baca semua berita tentang Telegram di Brasil di @tginfobr.
Sumber: https://tecnologia.ig.com.br/2022-05-12/telegram-muda-regras-idade-minima-brasil.html
#Brazil
Brasil telah mencabut keputusan untuk memblokir Telegram
Ketua Mahkamah Agung Brasil, Alexander de Moraes, membatalkan keputusan yang ditandatangani sebelumnya untuk memblokir Telegram di negara itu.
Moraes menjelaskan bahwa administrasi messenger memenuhi persyaratan yang ditetapkan untuk Telegram untuk terus bekerja di Brasil. Dalam hal ini, kunci diatur.
Kami mencari sukarelawan dari Brasil yang akan membantu kami menavigasi situasi di sekitar Telegram dengan lebih baik di negara ini. Tulis ke @infowritebot.
#Brazil