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

Резултати

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

Пребарај: #noob

当前筛选 #noob清除筛选
Pensive|

@PensivePost · Post #5170 · 06.05.2021 г., 06:10

I knew a girl who liked to draw, Pictures for only her eyes. She was more artistic late at night. Her drawings were different, No paper, No pen. But she needed a bandage, And wore long sleeves twenty-four/seven. We stood by the river, Under the stars, When she rolled up her sleeves And showed me her scars. She felt embarrassed and stared at her shoe. Then I rolled up my sleeves and whispered, "I draw too." #review#yourreview#noob

Pensive|

@PensivePost · Post #4753 · 17.01.2021 г., 14:31

Honesty for one, behold my love. I'll come in your dreams, For every night that I'm gone. Honesty for one, Behold my Love. #review#noob#prose Author's note: This might not make sense because: There's a song that I only remember by the deep voice of the singer, the melody and the vague-not-so-understood lyrics. These are the words that match that voice and my feelings. And obviously not the exact lyrics.

Pensive|

@PensivePost · Post #5159 · 01.05.2021 г., 16:22

It came from something we can't even see, It took so many lives and gave us the malady, The death, the pain, the anger the disability, Old people say they never witnessed such calamity. With heavy heart, Hope is alive and this is the fact, May the God help us to face all of this, Some people are still doing something wrong, Hope they'll get the fruits of their Unholy act. #anon #noob #review

Pensive|

@PensivePost · Post #5158 · 01.05.2021 г., 16:21

It came from something we can't even see, It took so many lives and gave us the malady, The death, the pain, the anger the disability, Old people say they never witnessed such calamity. With heavy heart, Hope is high, will is strong and this is the fact, May the God help us to face all of this, Some people are still doing something wrong, Hope they'll get the fruits of their Unholy act. #anon #noob #review

Pensive|

@PensivePost · Post #5157 · 01.05.2021 г., 16:20

It came from something we can't even see, It took so many lives and gave us the malady, The death, the pain, the anger the disability, Old people say they never witnessed such calamity. With heave heart, Hope is high, will is strong and this is the fact, May the God help us to face all of this, Some people are still doing something wrong, Hope they'll get the fruits of their Unholy act. #anon #noob #review

Elf Crypto VIP

@elfcryptovip · Post #12659 · 11.05.2026 г., 10:34

📍 List of abbreviations commonly used in cryptocurrency trading: #ALTCOIN = Alternate cryptocurrency except bitcoin #SHITCOIN = A coin with no potential value or use #BEAR | #BEARISH = Negative price movement #BULL | #BULLISH = Positive price movement #LONG = Margin buy position #SHORT = Margin sell position #BTFD = Buy The Fucking Dip #DILDO = Long green or red candles 😆 #DYOR = Do Your Own Research #FA = Fundamental Analysis #TA = Technical Analysis #FOMO = Fear Of Missing Out #JOMO = Joy Of Missing Out #FUD = Fear Uncertainty & Doubt #HODL = Hold a position #MCAP = Market Capitalization #MOON = Continuous upward movement of price #OTC = Over The Counter #PUMP = Upward price movement #DUMP = To sell off a coin #REKT = When you have a bad loss #WHALE = Very wealthy trader/Market mover #AMA = Ask me anything #ATH = All Time High #ATL = All Time Low #DLT = Distributed ledger technology #IMO = In My Opinion #LAMBO = Lambo is symbol that becomes an elusive goal for most investors #NOOB = A person who is inexperienced #SAFU = Secure Asset Funds for Users #SHILL = Holder of altcoin who just wants to promote it for his own benefit ✅@ElfCryptoVIP