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

Резултати

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

Пребарај: #quasark

当前筛选 #quasark清除筛选
Quasark.io - Announcement

@quasark_channel · Post #8 · 05.07.2023 г., 15:08

💥CLOSED BETA TESTERS SELECTED! Attention all #QuasarK enthusiasts! We are thrilled to announce that we have selected our closed beta testers for the upcoming QuasarK app on iOS and Android 🎉 To our selected beta testers, congratulations! 🥳 You are the chosen ones who will get an exclusive sneak peek 👀 into the app's features, functionalities, as well as a bunch of exciting perks. Your valuable feedback and insights will help us refine and enhance🚀 the QuasarK experience for everyone. ✅ We have granted all beta testers a special role in our QuasarK Discord server. This role comes with access to a private channel dedicated to the closed beta testing. There, we will keep you updated on all the important information📩 regarding the app's access, updates, and any announcements related to the beta testing phase. Make sure to check your Discord notifications for the role assignment and say hello in the private chats📲💬 We are incredibly excited 🙈 to have you on board, and we can't wait to embark on this beta testing journey together. Your input and feedback will play a vital role in shaping the final release of QuasarK 💫, and we greatly appreciate your dedication and involvement in this process. Thank you once again 😍 for being part of the QuasarK community and for your continued support. Stay tuned🔔 for more updates, surprises, and the official launch of QuasarK coming soon!

Hashtags

Quasark.io - Announcement

@quasark_channel · Post #7 · 04.07.2023 г., 07:49

📢CLOSED BETA WHITELIST CLOSED Attention, QuasarK Community: the application period for our closed beta is now officially closed. We want to express our heartfelt thanks ❤️ to everyone who applied and showed their interest in being a part of this exclusive testing phase. Your support and enthusiasm mean the world to us! 👏 🚀 But hold on tight, because the journey is just getting started! In a matter of days we’ll be reaching out to our whitelisted beta testers🏆. If you made it to the whitelist, keep an eye on your notifications and direct messages 📩 as we will be sharing important updates and instructions with you. BEWARE OF SCAM! Stay tuned for more updates and announcements 👀 as we continue to make progress towards the launch of QuasarK. We appreciate your ongoing support and look forward to embarking on this exciting journey together! #QuasarK#ClosedBeta#BetaTesters#ComingSoon

Quasark.io - Announcement

@quasark_channel · Post #5 · 28.06.2023 г., 13:01

💫📝 JOIN QUASARK BETA Calling all crypto enthusiasts! We are thrilled to announce that QuasarK is to launch its closed beta and we need OGs willing to be the first to experience the power and convenience of the next-gen wallet 🙌 🔍 Become a Beta Tester and play an active role in refining and improving 💎 the wallet before its public release. And your effort will be rewarded 💰 💥 How to Join QuasarK Beta 1️⃣ Participate in this campaign: https://zealy.io/c/quazark/invite/yJwJUITfB-ehsbeVWcaOP 2️⃣ Complete all the tasks and get 'QuasarK Closed Beta' Discord role. Lucky beta testers will be selected from all holders of this role! 🚀 Don't miss this incredible opportunity to be at the forefront of crypto innovation. Join the QuasarK beta testing program ✅, contribute to the development of a game-changing multichain wallet. The number of testers is very limited, and the rewards are well-worth it! Together, let's revolutionize the way we manage our digital assets! #QuasarK#Crypto#DeFi#Web3#Beta

Quasark.io - Announcement

@quasark_channel · Post #6 · 30.06.2023 г., 12:53

🚀 Last Call for the QuasarK Closed Beta Whitelist Are you ready to experience the future of cryptocurrency wallets? The countdown is on ⏰, and we don't want you to miss out on this exciting opportunity! Here's why you want to be part of our closed beta: 1️⃣ Unrivaled Security: Quasark ensures the safety of your funds like never before. Rest easy, knowing your assets are protected. 2️⃣ User-Friendly Interface: Effortlessly navigate through features, send and receive funds, and stay in control of your financial future. 3️⃣ Cutting-Edge Features: From instant swaps to customizable interface, we've got you covered with a suite of powerful tools. 4️⃣ Prices&Market trends: Access insightful charts and information to make informed investment decisions. 👉 Don't wait any longer! Secure your spot before SUNDAY: https://zealy.io/c/quazark/invite/yJwJUITfB-ehsbeVWcaOP #Quasark#CryptoWallet#ClosedBeta#DigitalAssets#DeFi