Можно ли в 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
☀️Good Morning, Traders!☕
Every sunrise brings a new chart, a new candle, and a new opportunity. 📊
Today is not just another day — it’s another chance to grow your account, your mindset, and your confidence. 💪
🎯Remember:
Trading is not just about profits — it’s about discipline, patience, and consistency.
Don’t chase the market… understand it.
Don’t fear losses… learn from them.
💼Pocket Option gives you the platform.
Your mindset gives you the power.
Now go make today count. 🚀
#BinaryOptions#PocketOption
New week = New opportunities 🚀
Every Monday is a reminder that:
“If yesterday was tough, today is a fresh start.”
In trading, your greatest skills are patience and consistency.
Don’t just trade — plan, learn, and grow.
📈 Stay focused.
💡 Stay disciplined.
🔥 Stay motivated.
Let’s make this week profitable!
💲
#MondayMotivation#BinaryOptions#TradingMindset
☀️Good Morning Traders!
📈
A new day brings new opportunities — the market never sleeps, and neither do the smart traders. 🔥
Focus on discipline, patience, and perfect entries today. Remember — profits come to those who wait for the right moment, not every moment! 💰
💰 Stay focused
📊 Trust your strategy
🚀 Let’s make today a winning day!
#BinaryOptions#TradingMindset#MorningVibes
Halloween Weekend Grind Never Dies! 💀📈
Even when the market’s sleeping, real traders stay awake — dreaming big, planning moves, and leveling up. ⚡
Tonight’s vibe:
No fear, no FOMO — just fun, freedom & future goals. 🍾🔥
When Monday hits, we rise again — sharper, smarter & ready to haunt those charts! 👻
📈
#TraderMindset#BinaryOptions#realbinaryoptionss
🌈 | New Week, New Profits
💵
Good morning traders! ☕️
A brand new week means fresh opportunities to make smart moves and grow your account. 🚀
✅ Stay focused
✅ Follow the signals
✅ Manage your risk
✅ Trust the process
Let’s start this Monday strong and make it a week full of green trades! 📈🔥
#BinaryOptions#TradingSignals#MondayMotivation#RealBinaryOptions
🚀WEEKEND MODE: PREPARE TO DOMINATE!🔥🚀
Champions don’t rest… they prepare. 💪📈
While others relax, real traders level up.
📊 Study the charts
🧠 Improve your strategy
🔍 Analyze your mistakes
🎯 Plan for next week
Remember —
Next week’s profits are built on this weekend’s preparation 💸
Discipline + Patience = Big Wins 🏆
If you’re serious about success, weekends are your secret weapon.
Drop in the comments 👇
“READY TO WIN 💥”
We don’t depend on luck.
We trade with skill. 🔥
#WeekendVibes#TraderMindset#BinaryOptions#StayFocused
⚡️PRO THUNDER V12: THE ELITE TRADING STANDARD⚡️
Stop settling for repainting tools and local scripts. Pro Thunder V12 is the culmination of 5 years of development by SS7Trader Ltd.
Why the pros choose V12:
🚫100% Non-Repaint: Signals are fixed. What you see is what you get.
🧠Neural Network AI: Powered by advanced AI to filter market noise.
✅Registered Authority: Built by a verified company, not an anonymous team.
⏳5-Year Legacy: Continuous evolution and optimization since 2021.
🎯 Pure Simplicity: Clear Buy/Sell signals with a fixed 5-minute expiry.
🌍 Universal: Works on any broker, any chart, and any timeframe.
━━━━━━━━━━━━━━━━
🚀 JOIN THE ELITE. STOP GUESSING.
🔗https://ss7trader.com/product/pro-thunder-v12/
✈️ Contact: https://t.me/SSsevenTrader
#SS7Trader#ProThunderV12#TradingAI#NonRepaint#BinaryOptions
⚡️PRO THUNDER V12: THE ELITE TRADING STANDARD⚡️
Stop settling for repainting tools and local scripts. Pro Thunder V12 is the culmination of 5 years of development by SS7Trader Ltd.
Why the pros choose V12:
🚫100% Non-Repaint: Signals are fixed. What you see is what you get.
🧠Neural Network AI: Powered by advanced AI to filter market noise.
✅Registered Authority: Built by a verified company, not an anonymous team.
⏳5-Year Legacy: Continuous evolution and optimization since 2021.
🎯 Pure Simplicity: Clear Buy/Sell signals with a fixed 5-minute expiry.
🌍 Universal: Works on any broker, any chart, and any timeframe.
━━━━━━━━━━━━━━━━
🚀 JOIN THE ELITE. STOP GUESSING.
🔗https://ss7trader.com/product/pro-thunder-v12/
✈️ Contact: https://t.me/SSsevenTrader
#SS7Trader#ProThunderV12#TradingAI#NonRepaint#BinaryOptions
⚡️PRO THUNDER V12: THE ELITE TRADING STANDARD⚡️
Stop settling for repainting tools and local scripts. Pro Thunder V12 is the culmination of 5 years of development by SS7Trader Ltd.
Why the pros choose V12:
🚫100% Non-Repaint: Signals are fixed. What you see is what you get.
🧠Neural Network AI: Powered by advanced AI to filter market noise.
✅Registered Authority: Built by a verified company, not an anonymous team.
⏳5-Year Legacy: Continuous evolution and optimization since 2021.
🎯 Pure Simplicity: Clear Buy/Sell signals with a fixed 5-minute expiry.
🌍 Universal: Works on any broker, any chart, and any timeframe.
━━━━━━━━━━━━━━━━
🚀 JOIN THE ELITE. STOP GUESSING.
🔗https://ss7trader.com/product/pro-thunder-v12/
✈️ Contact: https://t.me/SSsevenTrader
#SS7Trader#ProThunderV12#TradingAI#NonRepaint#BinaryOptions
⚡️PRO THUNDER V12: THE ELITE TRADING STANDARD⚡️
Stop settling for repainting tools and local scripts. Pro Thunder V12 is the culmination of 5 years of development by SS7Trader Ltd.
Why the pros choose V12:
🚫100% Non-Repaint: Signals are fixed. What you see is what you get.
🧠Neural Network AI: Powered by advanced AI to filter market noise.
✅Registered Authority: Built by a verified company, not an anonymous team.
⏳5-Year Legacy: Continuous evolution and optimization since 2021.
🎯 Pure Simplicity: Clear Buy/Sell signals with a fixed 5-minute expiry.
🌍 Universal: Works on any broker, any chart, and any timeframe.
━━━━━━━━━━━━━━━━
🚀 JOIN THE ELITE. STOP GUESSING.
🔗https://ss7trader.com/product/pro-thunder-v12/
✈️ Contact: https://t.me/SSsevenTrader
#SS7Trader#ProThunderV12#TradingAI#NonRepaint#BinaryOptions
⭐️See What Our Clients Are Saying About SS7 Trader!
⭐️
Our traders' success and satisfaction are the foundation of our brand. Discover why the community trusts 'The Binary Experts' to navigate the markets! 📈
👇 Click the link below to read real success stories and testimonials from our amazing community:
🔗https://ss7trader.com/reviews-2/
#SS7Trader#BinaryOptions#TradingReviews#ForexSuccess#TheBinaryExperts
⭐️See What Our Clients Are Saying About SS7 Trader!
⭐️
Our traders' success and satisfaction are the foundation of our brand. Discover why the community trusts 'The Binary Experts' to navigate the markets! 📈
👇 Click the link below to read real success stories and testimonials from our amazing community:
🔗https://ss7trader.com/reviews-2/
#SS7Trader#BinaryOptions#TradingReviews#ForexSuccess#TheBinaryExperts