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

Резултати

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

Пребарај: #bcmc1

当前筛选 #bcmc1清除筛选
AIRDROPS BOSS

@airdropsboss · Post #852 · 25.12.2021 г., 13:59

To the beautiful and wonderful BeforeCoinMarketCap Community! Sincerest wishes for health, happiness, and peace during this Holidays season and throughout the coming year! We thank you all for your unlimited contribution. We hope you stay with us, there are many interesting things this coming year! Let the spirit of love gently fill our hearts and homes. In this loveliest of seasons may you find many reasons for happiness. From all of us at BeforeCoinMarketCap. 💝 #BCMC1#BeforeCoinMarketCap#Crypto#BCMCToken#Airdrop#Bounty

AIRDROPS BOSS

@airdropsboss · Post #853 · 28.12.2021 г., 13:42

Dear community! 💙 BCMC1 People IEO Airdrop⬇️⬇️⬇️ @bcmc_peopleIEO_airdropbot ✅ Please complete all the tasks and submit details correctly. 💰 Rewards: - If you complete all tasks you will get 450 BCMC1. 📊Market: CoinMarketCap 💧BOUNTY💧 ⏰ Airdrop will end on (UTC) or when there are 5,000 participants. #BCMC1#BeforeCoinMarketCap#BCMC#Crypto#BCMCToken#Airdrop

AIRDROPS BOSS

@airdropsboss · Post #830 · 15.11.2021 г., 14:59

🚀BeforeCoinMarketCap NEW AIRDROP🚀 💵Total Reward: 550 BCMC1 💰 Value: $8 📊Market: CoinMarketCap click here⤵️ 💎Airdrop Bot💎 ☝️Don't miss out on MLM (Ongoing tokens sale with limited pool). 🥳 Invite buyers with your referral links and earn 10% GOOD LUCK TO EVERYONE!!!✊🏻 💠Telegram 💠Telegram Channel 💠Twitter 💠Facebook 💠LinkedIn 💠YouTube 💠Website #BCMC1#BeforeCoinMarketCap#BCMC#Crypto#BCMCToken#Airdrop

AIRDROPS BOSS

@airdropsboss · Post #854 · 31.12.2021 г., 10:57

💧BeforeCoinMarketCap BOUNTY💧 (For 100 participants only💯) Make a video about our platform: Post it on your official YouTube channel (3-5 minutes) $50 - $100 in BCMC1 token. We take into account the length and quality of the content. Example: Please watch this videos for instructions: https://youtu.be/8t1ucZFnyL8 & https://youtu.be/aYrpgGpI074 1 Best video will receive 15,000BCMC1 ($200) and will posted on our social channels.🏆 Mandatory: ✅Describe the People IEO. (Community voting) ✅Describe the People IEO. (Participant projects) ✅Explain the MLM system (Ongoing token sales) ❗️Notice: The channel must have Minimum of 1000 subscribers. Your email will be blacklisted if you submit an old video link or if you do not follow the instructions given. #BCMC1#BeforeCoinMarketCap#BCMC#Crypto#BCMCToken#bounty#Bounty

AIRDROPS BOSS

@airdropsboss · Post #829 · 13.11.2021 г., 08:32

💎 BeforeCoinMarketCap New BOUNTY 💎 For 100 participants only💯 Bounty Tasks✅ Make a video about our platform: Post it on your official YouTube channel (3-5 minutes) $50 - $100 in BCMC1 token. We take into account the length and quality of the content. 📍Mandatory: 1. Describe the search window. 2. Describe the Announcement window 3. Explain the MLM system (Ongoing token sales): 4. Describe the promotion website Best video will receive 20,000BCMC1 ($300) and will posted on our social channels. 📍Bounty Google Form Notice: The channel must have Minimum of 1000 subscribers. Your email will be blacklisted if you submit an old video link or if you do not follow the instructions given. #BCMC1#BeforeCoinMarketCap#BCMC#Crypto#BCMCToken#Bounty