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

Резултати

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

Пребарај: #suggestions

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

@PensivePost · Post #5769 · 27.05.2022 г., 04:17

Chapter 1:The cuckoo's nest The irksome sound coming from someone's radio , "it must be morning " i muttered , tho i dont usually wake up this early on a holiday like this , so i tried to cover myself in the warmth of blanket but not enough to insulate that annoying noise and so i gave up on my dream. The sun was dim today quite unusual day for a summer . A strong pingent smell caught my glemse , after using my brain and nose i was able to find the cordinates of its origin. "Its coming from my balcony "i shouted , I jumped out of my blanket and opened the balcony , There was a dead cuckoo lying on the floor , might have fallen from its nest . I usually come to see this cuckoo been feed by a small Canary , that was a quite appealing view to watch or rather entertaining. The decaying body of cuckoo was alluring alot of bugs and ants, "Someone will live on someone's death" i said on a quavering voice , My neighbour was also in his balcony watching that cuckoo's , his balcony was just 1 feet away from mine . Unlike me his balcony was been decorated with lot of flowers , pot were hanging on the side of his wall. A green fluffy carpet all over his wall, giving more athestic look to his balcony , on the other hand my balcony have alot of poops of the birds which i never bothered to clean , a rusty chair which got its rust by weting in the rain , some clothes hanging here and there , being just 1 feet away and paying the same rent there was a lot of difference in our balconies , or rather alot of difference in our personality . He usually come to water his plants tho we never talked before. After spending few more minutes in balcony gloring the blueness of sky , I went back to my room , my stomach was starving by the time , I quickly went to check on my fridge for something to eat , even my bad luck is unlucky ,it just contains some rotten yogurts , broken beer bottles , a pouch of sous which is expired , a frozen fish . I went to my kitchen and found that i was out of instant noodles too. #review #novel #suggestions

GitHub Trends

@githubtrending · Post #15383 · 02.01.2026 г., 11:30

#go#customer#feature_request#feedback#ideas#suggestions Fider is a simple tool for collecting customer feedback, feature requests, and votes to prioritize what users want most. Use Fider Cloud for quick managed setup or self-host it free on your servers. Customize it, invite users to suggest ideas, vote, and discuss, then update statuses like "planned" or "done" to keep them informed. This saves time guessing needs, boosts customer loyalty through engagement, and helps build better products efficiently. https://github.com/getfider/fider