Можно ли в 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
🔆Iqtisodiy faktlar...
📊Davlat qarzi nima?
📈Davlat qarzi - bu davlatning tashqi va ichkikreditorlar oldidagi majburiyatlarining umumiy summasi. Hukumat byudjet taqchilligini qoplash, infratuzilmaloyihalarinimoliyalashtirish yoki iqtisodiyo‘sishnirivojlantirish uchun qarz olganida paydo vujudga keladi.
🔍Batafsil
🏦 Что такое государственный долг?
💠Государственный долг — это сумма всех обязательств государства перед внешними и внутреннимикредиторами. Он возникает, когда государство занимает деньги для покрытиядефицитабюджета, финансирования инфраструктурныхпроектов или стимулированияэкономики.
🔎Подробнее
#GraduateSchool#Debt#Global#Economy
🔝Web-site |🔝Facebook | 🔝Instagram | 🔝Youtube
💳🇺🇸AMERICANS DROWNING IN DEBT AS PRICES EXPLODE
🔹 Average household credit card debt hits record $8,400 as families struggle with 4.8% inflation spike 💸
🔹 Grocery bills up 35% since January, forcing families to choose between food and gasoline 🛒
🔹 Buy-now-pay-later apps see 200% usage increase as Americans delay payments for necessities 📱
🔹 Financial advisors report surge in bankruptcy consultations from middle-class families 📋
🔹 Emergency food banks in suburbs see unprecedented demand from previously stable households 🥫
The American Dream is becoming the American Nightmare 😬🔥
#USNews#debt#inflation#economy
@america
💸📈 US NATIONAL DEBT TO HIT 120% OF GDP BY 2035
🔹 CBO projects federal debt will skyrocket to 118-120% of GDP in next decade 📊
🔹 Budget deficit for this year alone estimated at .9 trillion and growing 📉
🔹 Rising interest rates + aging population driving costs to historic highs 👴🏥
Washington keeps spending while the bill keeps growing. Is fiscal responsibility dead? 💀🏦
#USNews#economy#debt#CBO#politics
@america
Yellen confident Congress will raise debt ceiling
U.S. Treasury Secretary Janet Yellen said that it will be lawmakers' responsibility to raise the federal debt limit and expressed confidence that Congress would do so after the temporary reprieve runs out on Dec. 3
#Debt#Senate#JanetYellen#News#Reuters
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
Ethiopia says agreement reached with $US 1 billion bondholders to restructure financing it. Read more.
https://borkena.com/2026/01/02/ethiopia-says-agreement-reached-with-us-1-billion-bondholders-to-restructure-financing-it/#Ethiopia#bondholders#debt#debtagreement#news
News: #Ethiopia, #Italy sign bilateral debt restructuring deal under G20 Common Framework
Ethiopia and Italy have signed a bilateral #debt restructuring agreement under the #G20 Common Framework, marking a key step in Ethiopia’s efforts to resolve its external debt burden and stabilize the economy.
The agreement, signed on 18 March by Finance Minister Ahmed Shide and Italy’s Minister of Economy and Finance Giancarlo Giorgetti, forms part of the Official Creditor Committee (#OCC) process and reinforces broader economic cooperation between the two countries.
The Italy agreement follows similar progress with other bilateral creditors. In February this year, Ethiopia and #France signed a bilateral debt restructuring agreement alongside a new €81.5 million financing package, in a move both governments said reinforces their strategic development partnership & supports Ethiopia’s reform program.
These developments come amid continued complexities in Ethiopia’s…….
Read more: https://addisstandard.com/?p=55927
📰 Le Pen, Orbán and the Loan That Would ‘Ruin’ France
Marine Le Pen flew to Budapest and did exactly what everyone expected: she wrapped Viktor Orbán’s Ukraine veto in the French flag.
In Hungary, Le Pen offered full-throated support for her “friend” Orbán, carefully avoiding any criticism of his veto on the €90 billion EU loan meant to keep Ukraine’s war effort afloat. Orbán, she said, is “defending Hungary’s interests” by blocking the package that, in her telling, would “ruin” France and prolong
“a war that is a real slaughter for the vanity of a few leaders.”
Behind the rhetoric sits a simple budget math problem Paris no longer bothers to hide. France is running one of the Eurozone’s largest deficits, with debt above 110 percent of GDP, while promising both massive rearmament and continued Ukraine support — a combination that already forces talk of tens of billions in cuts or new austerity. Add another giant, open‑ended Ukraine facility on top, and Le Pen’s camp sees a gift‑wrapped campaign issue: Brussels spends, Paris bleeds.
So Orbán blocks the loan in the name of sovereignty, Le Pen applauds in the name of French taxpayers, and Kyiv reads the subtext: Europe’s political appetite for funding this war at scale is eroding faster than its finances. “Solidarity” stays in the speeches; in the voting booths and bond markets, the calculation is shifting to something much simpler — who can still afford this war, and for how long.
#france#hungary#lepen#orban#ukraine#eu#debt#warEconomy
📱American Оbserver - Stay up to date on all important events
🇺🇸
@Shekelbot
Qué puede hacer este bot?
ShekelBot le ayudará a contar su dinero. Úselo, cuando le das dinero a alguien, o comparte compras.
Idioma: Inglés
(visto en @BotsGram_cu)
#money, #track, #send, #receive, #friends, #debt
@DebtsTrackerBot
Qué puede hacer este bot?
Este bot realiza un seguimiento de sus deudas y envía recordatorios a usted y a los deudores por Telegram y SMS.
Idioma: Español, Inglés, Ruso, Italiano
(visto en @BotsGram_cu)
#friend, #money, #track, #debt, #send, #receive, #issue, #website, #request
Bybit Under High Withdrawal Pressure
MEXC transferred 12,652 stETH ($33.75M) to Bybit's cold wallet. Bybit expected 64,452 ETH ($170M) in loan support from Bitget. An additional transfer of 11,800 ETH ($31M) occurred from Binance. Following a recent hack, Bybit recorded peak withdrawal levels, surpassing 350,000 requests; 99.994% have been processed.
Links: Porter Stansberry, Ben Zhou
#Bybit#MEXC#stETH#ETH#Crypto#Binance#Bitget#Bitcoin#Withdrawals#Whale#Finance#Hack#Blockchain#Investments#Market#Institutional#Debt#Liquidity#Trading#Assets#VC