Можно ли в 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
Central Bank Politicization in Ethiopia and Implications for Creditors. Read more.
https://borkena.com/2026/02/26/ethiopia-central-bank-politicization-in-ethiopia-and-implications-for-creditors/#Ethiopia#CentralBank#Bank
Nabiullina: Russia Faces Labor Shortage for the First Time
At the Alpha Summit, Central Bank Chair Elvira Nabiullina stated that modern Russia is experiencing an unprecedented labor shortage. This situation significantly impacts the economy and regulatory decisions. Nabiullina emphasized that more timely data would improve labor market analysis. Such a workforce deficit presents a new challenge for the country’s economy.
#Russia#CentralBank#Nabiullina#LaborMarket#Economy
The main news of Russia and the world ishere.
Russian Ministry of Economic Development Welcomes Central Bank’s Rate Cut
The Russian Ministry of Economic Development views the Central Bank’s seventh consecutive key rate reduction—from 15.5% to 15.0%—as a positive signal. The ministry highlights that easing monetary policy supports the economy’s shift toward sustainable growth, especially amid improvements in various sectors. This decision fosters business development and an improved investment climate.
“Lowering the rate is a crucial step to support the economy,” the ministry emphasized.
#Russia#Economy#CentralBank#KeyRate#EconomicDevelopment
The main news of Russia and the world ishere.
Russian Stock Market Opens Week with Moderate Decline
On April 29, the Moscow Exchange and RTS indexes fell 0.3%, reacting to the Central Bank of Russia’s cautious signals on monetary policy. Meanwhile, oil prices rose amid ongoing geopolitical tensions in the Middle East. Biggest losers included Group Pозитив (-2.2%), Yandex (-2.1%), and MMK (-1.8%). The official dollar rate stands at 75.53 rubles.
The market reflects both domestic and external challenges, showing investor caution.
#Russia#StockMarket#MoscowExchange#RTS#CentralBank
The main news of Russia and the world ishere.
Czech Central Bank Eyes Bitcoin Investment
Czech National Bank considers Bitcoin investment, stated Governor Aleš Michl. Proposal could diversify 5% of $146 billion reserves. Details: ForkLog
#CzechRepublic#Bitcoin#Crypto#Investments#CentralBank#Finance#AlešMichl#Reserves#ForkLog
Czech Bank Considers Bitcoin Investment
Aleš Michl, Governor of the Czech National Bank, suggests possible Bitcoin acquisition for diversification of foreign reserves. Board decision pending. Plans to raise gold reserves to 5% by 2028. Read more.
#CzechRep#Bitcoin#Finance#Investing#Gold#Reserves#CentralBank#Diversification#Crypto#Economy
⚠🇷🇺🏦 From July 25, your financial transaction in Russia may be blocked and refunds may be issued without your consent if it falls under the following categories:
📌 If It is made to an account in the bank's database for fraudulent transactions. It may be the sending or receiving bank's database.
📌 If there is information about the initiation of a criminal case from a client or other interested party
📌 If data is received from third-party organizations indicating a fraudulent transaction (for example, information from a telecom operator about unusual telephone activity for the client before the transfer of funds or an increase in the number of incoming messages from new numbers, including in instant messengers). Please note "including instant messengers")
On the same day, an order will also come into effect, according to which banks will have to return money, including those voluntarily transferred to fraudsters, to clients within 30 days of their request.
There are three grounds for this refund:
1. If the account to which the funds were transferred is in the fraudulent database;
2. If the bank did not notify the client about the transfer without his consent;
3. If the card was lost or used without the client's consent. In the latter case, the client must notify the bank about the loss, otherwise the bank has the right not to return the funds.
Subscribe:@nido_russia
https://t.me/nido_russia/1715
#news#Russia#finance#fraud#crime#centralbank#цб#сb
🚀 Bank of Japan Governor: Underlying Inflation Gradually Approaching Target
Bank of Japan Governor Kazuo Ueda stated that the underlying inflation rate is gradually accelerating towards the central bank's target. According to Jin10, Ueda emphasized the importance of monitoring inflation trends closely to ensure they align with the Bank of Japan's objectives. The central bank remains committed to its monetary policy framework to achieve stable price growth.
#BankOfJapan#Inflation#MonetaryPolicy#KazuoUeda#EconomicStability#CentralBank
U.S. Bitcoin Reserve Gains Traction
Growing support for a U.S. Bitcoin reserve post-Trump's inauguration. Estimates show a 64% chance for the reserve by 2025 via Polymarket. The proposal under the BITCOIN Act aims to accumulate 1M bitcoins over five years. Advocates highlight potential benefits while critics voice concerns about volatility and logistical issues. The initiative reflects a broader trend of governments exploring digital assets, alongside China's digital yuan advancements. More on the future implications of this movement on global finance.
#Bitcoin#Crypto#VC#Finance#DigitalAssets#Polymarket#Blockchain#Trump#Economy#Investment#Innovation#CentralBank#Cryptocurrency#DigitalDollar#China#Gold#Assets
🚀 Poland's Central Bank Governor: No Need for Rate Hike, Rate Cuts Paused
Poland's Central Bank Governor, Adam Glapiński, stated that there is no need to raise interest rates, and that the recent cycle of rate cuts has been paused. According to Jin10, Glapiński emphasized that the current economic conditions do not warrant an increase in rates, suggesting a stable monetary policy stance for the foreseeable future. This decision comes amid ongoing assessments of Poland's economic performance and inflation trends.
#Poland#CentralBank#InterestRates#MonetaryPolicy#Economy#Inflation#RateCuts
🚀 Venezuela's Inflation Rate Reaches 13.1% in March
Venezuela's central bank reported that the country's inflation rate reached 13.1% in March. According to Jin10, the inflation rate for the first quarter of 2026 was recorded at 71.8%, reflecting ongoing economic challenges in the nation.
#Venezuela#Inflation#Economy#CentralBank#EconomicCrisis #2026 #FinancialNews
🚀 Poland's Central Bank Keeps Benchmark Rate Unchanged at 3.75%
Poland's central bank has decided to maintain its benchmark interest rate at 3.75%, aligning with market expectations. According to Jin10, this decision reflects the bank's current monetary policy stance amid ongoing economic conditions. The unchanged rate suggests a cautious approach as the bank monitors inflationary pressures and economic growth. This move is consistent with the central bank's efforts to balance economic stability and inflation control.
#Poland#CentralBank#InterestRate#MonetaryPolicy#Inflation#EconomicGrowth#EconomicStability