Можно ли в 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
👍 This is why we're here!
Reached 9th TP in the VIP HTL channel!
With a 5% entry and a $1000 deposit, you could've earned $100!
🤑 All this profit could have been yours! 🔥ACCESS TO MANUAL TRADING for 70usdt/month
👉 We know how to earn 3-4-5 digit amounts without any deposit, with zero risk! Click the link, then START >>> Referral Program
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#cryptotrading#btc#AItrade
👆 OMG! Would you look at that 👀
Reached 9th TP in the VIP PRO channel!
Feels good to be a Propheta VIP, man... 🏖ACCESS TO MANUAL TRADING for 70usdt/month
⚡️Speed up your trading with Propheta AI Signals: real-time precision signals, elite-level automation, and Cornix integration — the future of trading is now! GET THE ACCESS TO AI SIGNALS
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#cryptomarket#cryptonews#AItrade
Now that's trading 👆🔥🔥🔥
Reached 9th TP in the VIP HTL channel!
Using a 5% entry you could've earned $205 with a $1000 deposit
🤑 All this profit could have been yours! 🔥ACCESS TO MANUAL TRADING for 70usdt/month
👉 Looking at those reports and can't believe what you're seing?
Go to our reports channel and audit us! @propheta_reports
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#CryptoSignal#AItrade#tradingviewindicator
👆 OMG! Would you look at that 👀
Reached 9th TP in the VIP CLUB channel!
Using a 5% entry you could've earned $453 with a $1000 deposit
VIPs getting filthy rich by the day ☺️🤑🤑ACCESS TO MANUAL TRADING for 70usdt/month
👉 Looking for a way to earn not only using signals?
Join our generous referral program and earn over $40 per recommendation!
Click the link, then START >>> Referral Program
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#AItrade#indicator#signalchannel
👀 Well, would you look at that! 👆
Reached 9th TP in the VIP HTL channel!
$215 in profits with a 5% entry and a $1000 deposit!
That's why we call it the "Money Printer" 💴💷💵ACCESS TO MANUAL TRADING for 70usdt/month
👉 OOooh yeah baby! And that's what we do every day! Every day milking those exchanges dry! Waiting for you: t.me/ProphetaAdmin_bot
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#AItrade#indicator#tradingindicator
👆 OMG! Would you look at that 👀
Reached 9th TP in the VIP HTL channel!
$303 in profits with a 5% entry and a $1000 deposit!
ACCESS TO MANUAL TRADING for 70usdt/month
📊Dominate the market with Propheta AI Analyzer: AI uncovers hidden patterns with razor-sharp analysis, adapts on the fly with slick customization, and delivers next-level pair hunting — your edge for strategic supremacy! GET THE ACCESS
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#bitcoinnews#buyeth#AItrade
Oops, we did it again 🤣
#MEWUSDT has reached 9th TP in the VIP HTL signals channel!👍
That's why we call it the "Money Printer" 💴💷💵ACCESS TO MANUAL TRADING for 70usdt/month
👉 Love the profits you're seeing, but can't afford the VIP cost?
Earn over $40 per one recommendation with zero risk using our referral program!
Click the link, then START >>> Referral Program
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#bitcoin#AItrade#trading
#BERAUSDT has reached 9th TP in the VIP CLUB signals channel!👍
$459 in profits with a 5% entry and a $1000 deposit!
Every day we're on fire! 🔥🔥🔥ACCESS TO MANUAL TRADING for 70usdt/month
👉 How to earn every month with zero risk?
Become Propheta partner with zero investment required!
Click the link, then START >>> Referral Program
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#AItrade#passiveincome#crypto
👆 Propheta living up to its name yet again 🔮
#BERAUSDT has just reached 9th TP in the VIP PRO channel!!!
Trade took just 2 days! 👍
You could've earned $599 with a 5% entry and a $1000 deposit!
🤑 All this profit could have been yours! 🔥ACCESS TO MANUAL TRADING for 70usdt/month
👉 We're sure that 99% of the signals channels simply cannot provide transparent performance reports like we do! Check it out - @propheta_reports
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#AItrader#AItrade#cryptotrading
👆 OMG! Would you look at that 👀
Reached 9th TP on our #GUNUSDT trade! 🔥🔥🔥
VIPs getting filthy rich by the day ☺️🤑🤑ACCESS TO MANUAL TRADING for 70usdt/month
👉 We will keep posting about how we earn money. Will you keep watching how someone else does it, or start earning yourself? Subscribe using our telegram bot: t.me/ProphetaAdmin_bot
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#AItrade#autotrading#tradingview
Oops, we did it again 🤣
#JELLYJELLYUSDT has just reached 9th TP in the VIP PRO channel!!!
Trade took just 1 hour! 👍
$161 in profits with a 5% entry and a $1000 deposit!
🤑 All this profit could have been yours! 🔥ACCESS TO MANUAL TRADING for 70usdt/month
👉 In our VIP community, not only will your deposit grow, but your skill as a trader as well!
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#tradingview#AItrade#buycrypto
#BABYUSDT has just reached 9th TP in the VIP PRO channel!!!👍
With a 5% entry and a $1000 deposit, you could've earned $643!
Every day we're on fire! 🔥🔥🔥ACCESS TO MANUAL TRADING for 70usdt/month
👉 Did you know that many traders use our performance reports to build their own trading strategy? That's how useful they are! Check them out: @propheta_reports
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#bitcoinnews#tradingview#AItrade