Можно ли в 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
🔠
🔠
🔠 Keychains can be found HERE
🔠
🔠
🔠 3D Printed Custom Night Lights (you send your image and I'll make it happen)
Offering custom 3D print services. Just message me for anything you may need (@teamanons1)
🔠
🔠
🔠 - 10g Year of the Snake Bill Shaped Bars 🐍
🔠
🔠
🔠- Premium Copper on website
1oz Colorized Patriotic Bars
1oz Silver Cards (different styles)
Back in stock 1g Team Anon Bars
👉 (@pmkllc)
Introducing 🔠🔠🔠
🔤🔤🔤🔤🔤🔤🔤 on the website here 👇
https://precious-metal-trump-notes.myshopify.com/collections/pmk-raffles?utm_campaign=share_orders&utm_content=android&utm_medium=product-links
Just click SHOP ALL on website to view ALL available products.
Check out all the items featured on Capt Kyle's Telegram 👇
https://preciousmetalkeepsakes.com/collections/capt-kyles-featured-products
Also. If you have a bigger budget and want some heavy metal. Please just message me (@teamanons1) or text me directly (number lower on post) prices are way lower for bigger budget!
I offer a WIDE variety of different types of Precious Metals from 1 gram to kilos (kilos are not on website only @pmkllc) always sigma tested and verified genuine .999 fs/fg or your money back! GUARNTEED!
Www.preciousmetalkeepsakes.com
Just click 🔤🔤🔤🔤🔤🔤🔤here
For any questions or concerns call or text anytime (502-252-1039) I'll be glad to help in anyway or message me here on telegram
📱 (@teamanons1)
I always have 👇
✅10oz bars of silver
✅5oz bars of silver
✅1oz Copper rounds. Several designs to choose from
✅Lots of other Precious Metal items available
⏰
🟥
⏰
🟥
⏰
🟥
⏰
🟥
⏰
🟥
Www.preciousmetalkeepsakes.com
🟥
⏰
🟥
⏰
🟥
⏰
🟥
⏰
🟥
⏰
➡️I have BETTER Prices and items not on website here @pmkllc
To follow new arrivals/Giveaways RAFFLES and everything Precious Metals Join our telegram page here (@pmkllc)
😇
🥰
🥰
🥰
🥰
🥰
🥰
🥰
😇
➡️Go to @pmkllc if your interested in having a chance of winning precious metals for a fraction of the price
➡️RAFFLES
I met Capt Kyle at the beginning of my Awakening journey and he has been nice enough to allow me to share my website on his channel and has never asked for anything in return. I greatly appreciate you Capt Kyle 🙏
Www.preciousmetalkeepsakes.com
#silver#preciousmetals#ta#staxxx
🦅🇺🇸💪🔥
🔠
🔠
🔠 Keychains can be found HERE
🔠
🔠
🔠 3D Printed Custom Night Lights (you send your image and I'll make it happen)
Offering custom 3D print services. Just message me for anything you may need (@teamanons1)
🔠
🔠
🔠 - 10g Year of the Snake Bill Shaped Bars 🐍
🔠
🔠
🔠- Premium Copper on website
1oz Colorized Patriotic Bars
1oz Silver Cards (different styles)
Back in stock 1g Team Anon Bars
👉 (@pmkllc)
Introducing 🔠🔠🔠
🔤🔤🔤🔤🔤🔤🔤 on the website here 👇
https://precious-metal-trump-notes.myshopify.com/collections/pmk-raffles?utm_campaign=share_orders&utm_content=android&utm_medium=product-links
Just click SHOP ALL on website to view ALL available products.
Check out all the items featured on Capt Kyle's Telegram 👇
https://preciousmetalkeepsakes.com/collections/capt-kyles-featured-products
Also. If you have a bigger budget and want some heavy metal. Please just message me (@teamanons1) or text me directly (number lower on post) prices are way lower for bigger budget!
I offer a WIDE variety of different types of Precious Metals from 1 gram to kilos (kilos are not on website only @pmkllc) always sigma tested and verified genuine .999 fs/fg or your money back! GUARNTEED!
Www.preciousmetalkeepsakes.com
Just click 🔤🔤🔤🔤🔤🔤🔤here
For any questions or concerns call or text anytime (502-252-1039) I'll be glad to help in anyway or message me here on telegram
📱 (@teamanons1)
I always have 👇
✅10oz bars of silver
✅5oz bars of silver
✅1oz Copper rounds. Several designs to choose from
✅Lots of other Precious Metal items available
⏰
🟥
⏰
🟥
⏰
🟥
⏰
🟥
⏰
🟥
Www.preciousmetalkeepsakes.com
🟥
⏰
🟥
⏰
🟥
⏰
🟥
⏰
🟥
⏰
➡️I have BETTER Prices and items not on website here @pmkllc
To follow new arrivals/Giveaways RAFFLES and everything Precious Metals Join our telegram page here (@pmkllc)
😇
🥰
🥰
🥰
🥰
🥰
🥰
🥰
😇
➡️Go to @pmkllc if your interested in having a chance of winning precious metals for a fraction of the price
➡️RAFFLES
I met Capt Kyle at the beginning of my Awakening journey and he has been nice enough to allow me to share my website on his channel and has never asked for anything in return. I greatly appreciate you Capt Kyle 🙏
Www.preciousmetalkeepsakes.com
#silver#preciousmetals#ta#staxxx
🦅🇺🇸💪🔥
🔠
🔠
🔠 Keychains can be found HERE
🔠
🔠
🔠 3D Printed Custom Night Lights (you send your image and I'll make it happen)
Offering custom 3D print services. Just message me for anything you may need (@teamanons1)
🔠
🔠
🔠 - 10g Year of the Snake Bill Shaped Bars 🐍
🔠
🔠
🔠- Premium Copper on website
1oz Colorized Patriotic Bars
1oz Silver Cards (different styles)
Back in stock 1g Team Anon Bars
👉 (@pmkllc)
Introducing 🔠🔠🔠
🔤🔤🔤🔤🔤🔤🔤 on the website here 👇
https://precious-metal-trump-notes.myshopify.com/collections/pmk-raffles?utm_campaign=share_orders&utm_content=android&utm_medium=product-links
Just click SHOP ALL on website to view ALL available products.
Check out all the items featured on Capt Kyle's Telegram 👇
https://preciousmetalkeepsakes.com/collections/capt-kyles-featured-products
Also. If you have a bigger budget and want some heavy metal. Please just message me (@teamanons1) or text me directly (number lower on post) prices are way lower for bigger budget!
I offer a WIDE variety of different types of Precious Metals from 1 gram to kilos (kilos are not on website only @pmkllc) always sigma tested and verified genuine .999 fs/fg or your money back! GUARNTEED!
Www.preciousmetalkeepsakes.com
Just click 🔤🔤🔤🔤🔤🔤🔤here
For any questions or concerns call or text anytime (502-252-1039) I'll be glad to help in anyway or message me here on telegram
📱 (@teamanons1)
I always have 👇
✅10oz bars of silver
✅5oz bars of silver
✅1oz Copper rounds. Several designs to choose from
✅Lots of other Precious Metal items available
⏰
🟥
⏰
🟥
⏰
🟥
⏰
🟥
⏰
🟥
Www.preciousmetalkeepsakes.com
🟥
⏰
🟥
⏰
🟥
⏰
🟥
⏰
🟥
⏰
➡️I have BETTER Prices and items not on website here @pmkllc
To follow new arrivals/Giveaways RAFFLES and everything Precious Metals Join our telegram page here (@pmkllc)
😇
🥰
🥰
🥰
🥰
🥰
🥰
🥰
😇
➡️Go to @pmkllc if your interested in having a chance of winning precious metals for a fraction of the price
➡️RAFFLES
I met Capt Kyle at the beginning of my Awakening journey and he has been nice enough to allow me to share my website on his channel and has never asked for anything in return. I greatly appreciate you Capt Kyle 🙏
Www.preciousmetalkeepsakes.com
#silver#preciousmetals#ta#staxxx
🦅🇺🇸💪🔥
🚀 PRECIOUS METALS | Silver Sees Intraday Rise Amid Decline in Crypto Volatility
Silver experienced a 1.49% increase in its intraday trading, reaching $76.364 per ounce. According to NS3.AI, the BTC Volatility Index decreased by 1.01%, settling at 44.20, while the ETH Volatility Index saw a 1.19% decline, reaching 63.83. These movements indicate a shift in market dynamics, with precious metals gaining traction as cryptocurrency volatility diminishes.
#PreciousMetals#Silver#Crypto#Volatility#MarketTrends#BTC#ETH
🚀 PRECIOUS METALS | Spot Gold Reaches $4,760 per Ounce with 0.86% Daily Increase
Spot gold prices have risen to $4,760 per ounce, marking a 0.86% increase within the day. According to Jin10, this upward movement reflects ongoing market dynamics influencing precious metals.
#PreciousMetals#Gold#SpotGold#MarketUpdate#CommodityPrices
🚀 PRECIOUS METALS | Gold and Silver Call Options Show Cautious Sentiment
Gold call options continue to be positioned for an upward move, although enthusiasm for betting on a significant rise remains moderate. According to Jin10, silver call options exhibit a more cautious stance, with limited bets placed on substantial upward movements.
#preciousmetals#gold#silver#calloptions#cautioussentiment
🚀 Silver Faces Technical Resistance Amid Analyst Predictions
Silver is encountering potential technical resistance around the $90 mark, according to analysts. Rashad Hajiyev has outlined a scenario where silver could reach approximately $300. According to NS3.AI, The Long Investor noted that silver previously peaked near $121 following a January chart call and is currently trading around $74, which the analyst considers attractive once more.
#Silver#TechnicalResistance#AnalystPredictions#PreciousMetals#Investment#Trading
🚀 Czech Central Bank Increases Gold Reserves to 76.6 Tons
As of the end of March 2026, the Czech Central Bank's gold reserves have reached nearly 77 tons, specifically 76.6 tons, according to data from the Czech Central Bank. According to Jin10, the World Gold Council reported that in February, the Czech Central Bank's gold reserves were approximately 75 tons, indicating an increase of 2 tons in February. The Czech Central Bank aims to increase its gold reserves to 100 tons by 2028.
#CzechCentralBank#GoldReserves#Gold#MonetaryPolicy#Finance#Economy#PreciousMetals
🚀 PRECIOUS METALS | Gold and Silver Prices Rise, Brent Crude Oil Declines
Gold prices have surged, reaching $4,800 per ounce, marking a 1.71% increase. According to Odaily, silver also experienced a significant rise, climbing by $2.00 to $76.10 per ounce, a 2.70% increase. In contrast, Brent crude oil saw a decline of over 1.00%, currently priced at $93.47 per barrel.
#gold#silver#preciousmetals#brentcrudeoil#oilprices#marketupdate#commodities
🚀 PRECIOUS METALS | Gold Prices in Uncertain Range Amid Middle East Tensions
Gold prices are currently positioned in the middle of a fluctuating range, with short-term predictions remaining uncertain. According to Jin10, the market is bracing for a potential escalation in Middle East conflicts, which has led to gold prices opening lower during the Asian trading session. Analysts suggest that the price of gold may continue to hover within this range, making it difficult to predict future movements in the short term.
#GoldPrices#MiddleEastTensions#PreciousMetals#MarketUncertainty#Gold#TradingSession
🚀 PRECIOUS METALS | Chinese Gold Jewelry Prices Drop Significantly
Gold jewelry prices in China have seen a notable decline today, according to Jin10. Several brands have reduced their prices by approximately 25 yuan compared to yesterday. The current prices are mostly in the range of 1,445 yuan to 1,450 yuan per gram.
#preciousmetals#gold#chinagold#goldprices#jewelryprices#marketnews
🚀 PRECIOUS METALS | Iran to Resume Gold Business Operations Nationwide Amid Ceasefire, Iranian Media Reports
Iranian media reports that Iran has decided to fully and formally resume operations of all gold business units nationwide starting Saturday, in light of the current ceasefire. According to Jin10, this decision marks a significant step in the country's efforts to stabilize its economy and restore normalcy in the gold market. The move comes as part of broader measures to enhance economic activities and support the precious metals sector, which has been impacted by recent geopolitical tensions. The resumption of gold business operations is expected to boost local trade and provide a positive outlook for the industry.
#Iran#Gold#PreciousMetals#Ceasefire#Economy#Geopolitics#GoldMarket#Trade