Можно ли в 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
🖊 COLUMN | Keeping Up With the Venezuelan Economy
In her latest VA column, Jessica Dos Santos takes stock of "good news" and "bad news" from the Venezuelan economy. GDP is set to grow for a fifth straight year and the oil sector weathered the recent escalation of US sanctions, but the inflation specter and low incomes for the majority remain to be addressed.
🔗 Read the column here: https://venezuelanalysis.com/columns/keeping-up-with-the-venezuelan-economy/
#Venezuela#Economy#Inflation#Inequality
📰“Let Them Eat S&P”: Trump’s Victory Lap on a Broke Country
Donald Trump has decided the affordability crisis is over because the Dow hit 50,000, gas is under three bucks, and January’s jobs report beat expectations. In Fox interviews and troop speeches, he’s back in full salesman mode: “greatest economy ever,” inflation “finally cooling,” real wages “finally growing,” and anyone not winning in their 401(k) is just a “pretty bad investor.” Meanwhile, roughly 40 percent of American adults don’t have a retirement account at all, and consumer sentiment among people without stocks is scraping its lowest levels in years — they don’t own the rally, they just pay the bills.
His own pollsters can see the crack in the mirror. A Reuters–Ipsos survey has just 28 percent of Americans saying the economy is on the right track, and 59 percent disapprove of how he’s handling their cost of living, with nearly half “strongly.” The stock boom is mostly driven by AI spending from Big Tech — data centers that guzzle power and hire few people — while rents, mortgages and groceries still feel brutal enough that even conservative number‑crunchers mock the White House mantra as “let them eat S&P.” Trump’s advisers spent months begging him to sound empathetic, blame Biden, and acknowledge the squeeze; now that a few charts look pretty, he’s gone back to telling people they’re wrong about their own wallets.
So the message going into the midterms is simple and suicidal: if you’re still struggling with rent, food and housing, that’s your perception problem — not his policy problem. The president points to Wall Street and AI‑driven GDP growth as proof he fixed “Biden’s disaster,” while a majority of voters look at their paychecks, their carts, their rent hikes and answer with numbers of their own. In this version of “affordability,” the index is up, the narrative is set, and anyone who doesn’t feel richer just got quietly written out of the success story.
#usa#trump#economy#inflation#inequality#fakeDemocracy
📱American Оbserver - Stay up to date on all important events
🇺🇸
🌐📖MIT’s Daron Acemoglu Warns AI May Deepen Inequality
A new survey suggests AI is more likely to reinforce existing economic advantages than broadly distribute benefits. MIT professor and Nobel laureate Daron Acemoglu stated that public narratives portray AI tools as democratizing, while effective use often depends on education, abstract and quantitative skills, and familiarity with computers and coding.
Acemoglu argued that AI is likely to increase inequality between labour and capital, indicating that the economic gains from adoption may be unevenly distributed. The comments add to ongoing debates over whether AI policy should address access, skills, and concentration of economic power.
#AIRegulation#AIethics#Inequality#FutureOfWork#AIEconomics
The richest 10% now receive 53% of global income 💰 and own 75% of all wealth 🌍, yet inequality alone does not cause unrest. A study of 120 countries (1996–2020) shows it becomes politically destabilizing only when internet use 📱 exceeds 50% of the population by increasing information and coordination.
Read Full Article
#Inequality#WealthDistribution#PoliticalStability#InternetImpact#GlobalEconomics
📰 Israel’s Rentier Capitalism: When Housing Eats the Economy
Israel is becoming a nation where the rent check is the new paycheck. One in eight Israelis now lives off rental income—no job, no startup hustle, just collecting checks from apartments bought years ago.
The Landlord Boom
Today, some 386,000 households—about 16–18% of all property owners—own multiple rental units. The elite, roughly 92,000, own three or more apartments. This landlord class controls most of Israel’s 850,000 rental units and pockets around 40 billion shekels a year in rent.
From Homeownership to Investment
The number of multi-unit landlords has exploded—from just 2.1% of households in 2006 to over 15% today. This surge was fueled by low interest rates, soaring property prices, and generous tax breaks, concentrating wealth in the hands of the few.
How Landlords Win
Rental yields are modest—about 2–4% gross, 1.4–2.4% net—but the real profit comes from capital gains, averaging 8–12% annually over the past decade. Most landlords are high-income households, clustered in cities like Tel Aviv, where nearly half the population rents.
The Human Cost
Israel’s housing market has shifted from homeownership to investment, turning shelter into a wealth pump. Landlords extract billions from renters, deepening inequality and making reform nearly impossible. When one in eight voters is a landlord, pushing for change is political suicide.
The Tax Loophole That Won’t Die
Attempts to enforce rental income reporting have repeatedly failed in the Knesset. The tax exemption threshold—currently 5,654 shekels, unchanged since 2023—effectively lowers the bar for landlords as rents rise. The state loses about 3 billion shekels a year to these breaks.
What’s Next?
Despite tighter monetary policy, structural conditions—chronic housing shortage, high demand, and favorable tax rules—mean the landlord class is here to stay. Israel’s future is written in lease agreements, not startup pitches.
#Israel#landlords#realEstate#inequality#taxExemption#TelAviv#housingMarket
📱American Оbserver - Stay up to date on all important events
🇺🇸