Можно ли в 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
#Oman🇴🇲
This oasis is called Vadi Bani Khalid and is one of the main attractions of the country. The Vadi landscape is striking in its diversity: here you will find both green oases with palm trees, and arid canyons with colorful cliffs. Picturers palm groves, transparent lakes and hills made of soft, golden sand. This place seems to invite us to plunge into an oasis of calm and harmony with nature.
🇮🇷🇴🇲According to an Associated Press report, Iran and Oman will collect tolls from all ships transiting the Strait of Hormuz during the two‑week ceasefire.
✍️ Recall Oman’s stance during the treacherous American attacks on the port of Salalah. Oman position and congratulate for the elect of new Iran's supreme leader so infuriated Trump that he even insulted the Sultan of Oman. Among the Arab nations, Yemen (Sana’a government) and Oman stood on the right side and did not bet on the losing horse! The current state of the UAE, Bahrain, Saudi Arabia, Kuwait, and Jordan is a testament to the wisdom of Omani policy.
#Iran#Oman
🇮🇷🤝🇴🇲 A new protocol has been finalized by Iran regarding the Strait of Hormuz and has been communicated to the IRGC Navy for implementation. This new protocol is based on the assumptions that, firstly, Iran’s enemies have no right to use the strait, and secondly, Iran must secure and compensate for all damages it has suffered through the strait.
👉Oman has agreed to cooperate with Iran’s new protocol in the Strait of Hormuz.
#Iran#Oman
🇮🇷🇴🇲Iran's Khatam al-Anbiya Central Headquarters: The Salalah port incident is suspicious
🔹The spokesperson for the Central Headquarters of Khatam al-Anbiya (PBUH), in response to the suspicious attack on Salalah port in Oman, said:
"The incident that occurred at Salalah port in the friendly, neighboring, and brotherly country of Oman appears very suspicious. The Islamic Republic of Iran is investigating this matter. The security and national sovereignty of Oman are respected by the Armed Forces of the Islamic Republic of Iran."
✍️ As we have said before, Iran has no intention of attacking civilian sites, and if it did, human casualties and financial damages in Arab countries would be unimaginable. The attack on Oman, which is considered a friend of Iran, is also very suspicious. Salalah port is also very far from southern Iran in terms of distance, and there is a possibility that this port was attacked by American drones. The U.S. is under pressure and spares no action against Iran!
#Iran#Oman
🇮🇷#Iran - 🇴🇲#Oman: Two alleged Iranian drones have struck Salalah Port in Oman, damaging port cranes. The Omani government has released a statement condemning the attack, stating that one port worker was “moderately injured.”
🇨🇳🇮🇷🇴🇲China urges Gulf states to unite against external interference amid widening conflict
China's foreign minister urged Gulf countries to unite to oppose external interference on March 2, after US-Israeli attacks on Iran triggered a widening conflict in the region.
China hoped that the Gulf states would strengthen unity and develop neighbourly friendship to "keep their future and destiny in their own hands", Chinese Foreign Minister Wang Yi said in a phone call with his Omani counterpart, according to a statement released by the ministry.
In a phone call with Iranian Foreign Minister Abbas Araqchi on the same day, Wang said he believed that Iran could maintain national and social stability as well as attach importance to the legitimate concerns of its neighbours, a separate statement showed.
#China#Iran#Oman
@asianomics
🇮🇷🎙Leader of Iran: The attacks in Oman and Turkey are not Iran's doing.
✉️ Seyyed Mojtaba Khamenei, the Leader of Iran, stated in this year's Nowruz message:
"I point out that the attacks which took place in Turkey and Oman—both of which have good relations with us—against certain locations in these countries were by no means carried out by the armed forces of the Islamic Republic or any other forces of the Resistance Front. "This is a deception employed by the Zionist enemy using the false flag tactic" to sow discord between the Islamic Republic and its neighbors, and it may also occur in some other countries."
#Iran#Oman#Turkey