TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #241 · 5 мај

Можно ли в 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

Hashtags

Резултати

Пронајдени 7 слични објави

Пребарај: #energycosts

当前筛选 #energycosts清除筛选
Crypto M - Crypto News

@CryptoM · Post #64952 · 10.04.2026 г., 12:07

🚀 Fed's Daly: High Oil Prices Could Boost Inflation but Impact Economic Growth Federal Reserve official Mary Daly has indicated that sustained high oil prices are likely to lead to increased inflation, according to Jin10. However, she also noted that these elevated prices could have a dampening effect on economic growth. Daly's comments highlight the complex interplay between energy costs and broader economic indicators, suggesting that while inflationary pressures may rise, the overall economic expansion could face challenges. #Fed#OilPrices#Inflation#EconomicGrowth#EnergyCosts#MaryDaly#FederalReserve

Crypto M - Crypto News

@CryptoM · Post #64508 · 09.04.2026 г., 04:33

🚀 Poland Likely to Maintain Interest Rates Amid Energy Cost Decline Poland is anticipated to keep its interest rates steady following a significant drop in energy costs. Bloomberg posted on X that the decrease in energy prices comes as a result of a two-week ceasefire in the US-led conflict in Iran. This development has alleviated fears of a resurgence in inflation, influencing Poland's monetary policy decision. The ceasefire has contributed to stabilizing the energy market, providing relief to consumers and policymakers alike. As Poland assesses the economic landscape, the focus remains on maintaining stability and preventing inflationary pressures. #Poland#InterestRates#EnergyCosts#Inflation#MonetaryPolicy#EconomicStability#Ceasefire#IranConflict

Crypto M - Crypto News

@CryptoM · Post #65173 · 11.04.2026 г., 16:05

🚀 USDi Stablecoin Seeks $1.5 Million in Seed Funding Amid Rising Inflation USDi, a stablecoin already in circulation, is aiming to secure approximately $1.5 million in seed funding. According to NS3.AI, the token is designed to track the U.S. Consumer Price Index (CPI) and is intended to increase in value with inflation, rather than maintaining a fixed nominal value of $1. Michael Ashton highlighted that the initiative comes at a time when U.S. inflation has surged to 0.9% in the past month, primarily due to energy costs linked to the ongoing conflict in Iran. #USDi#Stablecoin#SeedFunding#Inflation#CPI#EnergyCosts#IranConflict

Crypto M - Crypto News

@CryptoM · Post #64649 · 09.04.2026 г., 12:36

🚀 Mexico's Inflation Accelerates in March Amid Rising Global Energy Costs Mexico's inflation rate accelerated in March due to the impact of the Iranian conflict on global energy costs. According to Jin10, the country's statistics bureau reported that consumer prices rose by 4.59% year-on-year in March, slightly below analysts' median forecast of 4.64% but higher than February's rate of 4.02%. Core inflation, which excludes volatile food and fuel prices and is closely monitored by the central bank, slowed to 4.45% from February's 4.50%, also below the analysts' median forecast of 4.47%. In March, the largest price increases were seen in tomatoes, airline tickets, and prices at snack bars, restaurants, tortilla shops, and taco stands, while internet phone TV packages, eggs, and pork saw the largest declines. Despite the rising price pressures, the central bank expressed concerns about economic weakness. Although the Iranian conflict has led to a surge in crude oil prices, exacerbating inflationary pressures, Mexico's central bank views the conflict as posing a downside risk to the local economy. #Mexico#Inflation#EnergyCosts#IranConflict#CentralBank#ConsumerPrices#CoreInflation#Economy

Crypto M - Crypto News

@CryptoM · Post #64517 · 09.04.2026 г., 05:38

🚀 U.S. CPI Data to Reflect Impact of Iranian Energy Shock, Analysts Say U.S. CPI data released on Friday is expected to show the first significant impact of the Iranian energy shock, according to analysts at First Citizens Bank. The surge in energy costs is anticipated to accelerate overall inflation. According to Jin10, the bank's head of market and economic research noted that while core inflation remains significantly above target, the Federal Reserve is likely to 'ignore' the energy-driven inflation spike for now. He suggested that this stance reinforces the Fed's long-term position of maintaining current rates, linking potential rate cuts to the normalization of energy prices. #USCPI#IranianEnergyShock#inflation#FederalReserve#energycosts#ratecuts#FirstCitizensBank#economicresearch

Crypto M - Crypto News

@CryptoM · Post #64476 · 09.04.2026 г., 01:57

🚀 Mizuho Securities: Government Subsidies to Mitigate Japan's Energy Cost Impact Amid Middle East Conflict Mizuho Securities economists have indicated that despite the significant upward pressure on oil prices due to the Middle East conflict, government subsidies are expected to largely offset the impact on Japan's energy costs. According to Jin10, the economists noted that the effects on commodities, particularly food, will gradually become apparent, with inflation in these categories anticipated to peak between the spring and summer of 2027, implying a lag of four to six quarters. They further stated that due to the expected time required for securing the safety of the Strait of Hormuz and the full normalization of transportation, crude oil prices are likely to remain high in the short term. #Japan#EnergyCosts#MiddleEastConflict#OilPrices#GovernmentSubsidies#Inflation#Commodities#StraitOfHormuz#CrudeOil#EconomicImpact#MizuhoSecurities

Crypto M - Crypto News

@CryptoM · Post #64537 · 09.04.2026 г., 06:45

🚀 U.S. Inflation Pressures Persist as February PCE Data Anticipated The market anticipates that the U.S. February Personal Consumption Expenditures (PCE) data will indicate ongoing inflationary pressures. According to BlockBeats, consensus expectations suggest a month-on-month increase to 0.4% and a year-on-year rate holding at 2.8%, with core PCE year-on-year at approximately 3.0%, significantly above the Federal Reserve's 2% target. Analysts highlight that the current inflation rebound is primarily driven by rising commodity prices and increasing energy costs, while 'super core services inflation' remains notably sticky, making a short-term decline unlikely. In this context, the Federal Reserve is expected to maintain the interest rate range of 3.50%-3.75% at its April meeting, marking the third consecutive pause in rate cuts. Market pricing has also shifted rapidly, with over 97% of traders betting on no change in April, and expectations for rate cuts within the year have cooled significantly, with mainstream views shifting towards a 'later, less' easing path. #USInflation#PCEData#InflationPressures#FederalReserve#InterestRates#EnergyCosts#CommodityPrices#SuperCoreServices#MarketExpectations#RateCuts#USEconomy#FebruaryPCE#EconomicOutlook#FedPolicy#InflationRebound