Можно ли в 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
👀 Well, would you look at that! 👆
Reached 9th TP in just 1 day in the VIP PRO channel!
$609 in profits with a 5% entry and a $1000 deposit!
🤑 All this profit could have been yours! 🔥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!
#cryptoexchange#cryptobot#autotrading
Reached 9th TP in the VIP PRO channel!
Easy $604 with a 5% entry and a $1000 deposit!
That's why we call it the "Money Printer" 💴💷💵ACCESS TO MANUAL TRADING for 70usdt/month
🏆Flex your skills with Propheta AI Analyzer: smart AI analysis flips the market upside down, fast tweaks fit any style, and it’s your wingman for snagging top-tier trades! GET THE ACCESS
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#cryptoexchange#tradingview#crypto
👆 Propheta living up to its name yet again 🔮
Reached 9th TP in just 20 hours in the VIP PRO channel!
You could've earned $402 with a 5% entry and a $1000 deposit!
🤑 All this profit could have been yours! 🔥ACCESS TO MANUAL TRADING for 70usdt/month
🏆Flex your skills with Propheta AI Analyzer: smart AI analysis flips the market upside down, fast tweaks fit any style, and it’s your wingman for snagging top-tier trades! GET THE ACCESS
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#CryptoSignal#bitcoinnews#cryptoexchange
Oops, we did it again 🤣
Reached 9th TP in just 17 hours in the VIP PRO channel!
Easy $609 with a 5% entry and a $1000 deposit!
VIPs getting filthy rich by the day ☺️🤑🤑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!
#cryptoexchange#ethereum#tradingbot
👆 Propheta living up to its name yet again 🔮
Reached 9th TP in the VIP HTL channel!
$185 in profits with a 5% entry and a $1000 deposit!
VIPs getting filthy rich by the day ☺️🤑🤑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!
#ethereum#cryptoexchange#cryptocurrency
☄️🔖South Korean Police Crack Down on Crypto Fraud: 19 Arrested in 'Reading Room' Scam
🛡 South Korean police have made a major breakthrough in the fight against crypto fraud, apprehending 19 individuals involved in a deceptive "crypto reading room" scheme.
🔈 The gang operated through an open chat room, masquerading as seasoned traders and luring in unsuspecting investors seeking legitimate crypto advice.
💵However, instead of guidance, victims were duped out of a staggering $18.8 million by the cunning fraudsters.
🌐 Despite the arrests, the investigation is far from over, with at least six suspects still on the run. International cooperation through Interpol has been sought to bring them to justice.
❗️ Shockingly, the ringleader employed manipulative tactics akin to pig-butchering, promising jobs abroad only to exploit vulnerable individuals who fell into their trap.
#Cryptosignals#Cryptoinvesting
#Cryptoexchange
#Bitcoinprice
👆 Propheta living up to its name yet again 🔮
#ENAUSDT reached 9th TP in under 2 days!
Signal from our VIP PRO channel!
Easy $606 with a 5% entry and a $1000 deposit!
That's why we call it the "Money Printer" 💴💷💵ACCESS TO MANUAL TRADING for 70usdt/month
👉 Get dozens of signals like these daily!
Subscribe now >>> t.me/ProphetaAdmin_bot
Register and get bonuses up to $6,000
Binance | OKX | ByBit👈🏻click!
#signalchannel#cryptoexchange#bitcoinnews
#BABYUSDT has achieved 9th TP in our VIP HTL channel!
With a 5% entry and a $1000 deposit, you could've earned $302!
VIPs getting filthy rich by the day ☺️🤑🤑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!
#tradingviewindicator#ethereum#cryptoexchange
#MEWUSDT has achieved 9th TP in 11 hours in our VIP HTL channel!
Every day we're on fire! 🔥🔥🔥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!
#cryptoexchange#eth#ethereum
🌐 Former Kansas Bank CEO Pleads Guilty to $47M Crypto Embezzlement Scheme
💵 In a shocking turn of events, the ex-CEO of Heartland Tri-State Bank in Kansas has confessed to embezzling a staggering $47.1 million through a web of personal crypto purchases.
🕯 The fallout from this audacious scheme resulted in the bank's collapse last July, leaving investors with zero equity, according to the U.S. Attorney's Office for the District of Kansas.
📣 Identified as Shan Hanes, the 52-year-old mastermind behind this financial fiasco allegedly used cryptocurrencies as a smokescreen to hide mounting losses.
💬 "Hanes is not just a liar but also a master manipulator," stated Attorney Kate Brubacher, emphasizing the devastating impact on victims' life savings and retirement funds.
🛡 The FBI, FDIC, Federal Reserve Board, and FHFA are now jointly investigating this high-profile crypto case that has sent shockwaves through the industry.
✨ With a potential sentence of up to 30 years looming over him, Hanes awaits his fate at the sentencing scheduled for August 8th.
🟢The collapse of Heartland Tri-State Bank adds another layer to the ongoing debate about how traditional banks should navigate their relationship with the ever-evolving crypto ecosystem.
#Bitcointrading#Cryptosignals#Cryptoinvesting
#Cryptoexchange
#Bitcoinprice