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

Резултати

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

Пребарај: #gton

当前筛选 #gton清除筛选
TONlines – News

@tonlines · Post #7713 · 04.12.2025 г., 16:44

⚡️Gatto | Official Channel: $GTON Mine Event Details #GTON#TON The $GTON Mine event by Gatto | Official Channel offers players a chance to earn massive starting rewards and additional bonuses for successful captures, including TON rewards and items like the Delicious Gattobox. The event runs from 17:00 to 18:00 UTC. Source: link @tonlines

Hashtags

TONlines – News

@tonlines · Post #7674 · 01.12.2025 г., 19:47

⚡️Gatto Official Channel: Final Chance for $GTON Rewards #GTON#TON Gatto Official Channel announces the delayed snapshot date for $GTON participation. Participants have until December 2nd to adjust their game balance and qualify for a range of rewards, including pets, food, and NFTs. Staking concludes on December 29th. Source: link @tonlines

Hashtags

TONlines – News

@tonlines · Post #7554 · 21.11.2025 г., 10:06

Gatto Official Channel: Legendary Crocottery Event #TON#GTON The Gatto Official Channel announces the Legendary Crocottery event, a unique lottery where participants can win special prizes. Tickets are available for purchase with $GTON and TON, offering rewards such as gold coins, rare resources, and even Gen 9 pets. The event will culminate in a raffle on November 24th. Source: link @tonlines

Hashtags

TONlines – News

@tonlines · Post #7461 · 30.05.2025 г., 18:18

⚡️Gatto Official: Prize Marathon Results #TON#GTON The Gatto Official Channel announces the results of the prize marathon for Doge Pound pet owners. Participants had the chance to win various sets of $GTON and TON, with rewards being distributed by the end of the day. Source: link @tonlines

Hashtags

TONlines – News

@tonlines · Post #7385 · 27.05.2025 г., 09:11

⚡️Gatto Official Channel: Special Promotion for Krogurchikus Goods #TON#GTON Gatto Official Channel announces a two-day event featuring special items from Krogurchikus at discounts up to 80%. A unique "Shopaholic" promotion offers the chance to double your purchases by buying at least one item in each category, including food, mutagens, and gattoboxes. The event begins at 10:00 UTC with a restock on May 28 but reduced quantities. Source: link @tonlines

Hashtags

TONlines – News

@tonlines · Post #7298 · 20.05.2025 г., 14:39

⚡️Gatto | Official Channel: Exciting Gattobox Sales and Promotions #GTON#TON Gattoboxes are set to go on sale with two thrilling promotions. Participate in the "Who's Bigger" promotion by purchasing more gattoboxes than others to win mutagens and rare items. Additionally, try your luck in the "Lucky Chance" raffle by buying at least one GTON or TON gattobox. Source: link @tonlines

Hashtags

TONlines – News

@tonlines · Post #7447 · 30.05.2025 г., 11:04

Gatto: May $GTON Staking Rewards Completed #GTON#NFT The Gatto channel has announced the completion of the May $GTON staking, with participants receiving various in-game rewards and personalized recognitions. Long-term staking awards will also be distributed, with the next staking round set to begin on June 1. Source: link @tonlines

Hashtags

TONlines – News

@tonlines · Post #7697 · 03.12.2025 г., 15:46

Gatto | Official Channel: Creative Contest Announcement #Gatto#GTON Gatto | Official Channel has announced a creative contest to celebrate a birthday, inviting talented individuals to participate by creating drawings, stories, and crafts dedicated to Gatto. Participants are categorized by age, with the chance to win $GTON rewards. Submissions are open until December 8th. Source: link @tonlines

Hashtags

TONlines – News

@tonlines · Post #6778 · 15.04.2025 г., 13:50

⚡️Gatto Official Channel: PvP Battle Event with Rewards #GTON#Gatto The Gatto Official Channel invites players to join a special PvP event starting at 14:00 UTC. Participants who defeat the GTeam in consecutive battles can earn various rewards, including Silver Coins, Legendary Gattoboxes, and more. The event takes place exclusively on the European server and runs until April 15, 15:00 UTC. Source: link @tonlines

Hashtags

TONlines – News

@tonlines · Post #7648 · 29.11.2025 г., 12:12

Gatto | Official Channel Staking Update for December #staking#GTON Gatto | Official Channel announces a staking event in December for $GTON token holders. Participants can earn various rewards, including exclusive prizes and in-game items, by holding tokens from December 1st to 29th. Source: link @tonlines

TONlines – News

@tonlines · Post #7647 · 29.11.2025 г., 12:12

Gatto: December Staking Rewards Begin December 1 #staking#GTON Gatto | Official Channel announces a new staking initiative for $GTON, starting on December 1 and running until December 29. Participants will be rewarded with various prizes, including game items and tokens, depending on their stake tier. Source: link @tonlines

TONlines – News

@tonlines · Post #7642 · 28.11.2025 г., 15:33

Gatto | Official Channel: November $GTON Staking Completion #staking#GTON The Gatto | Official Channel successfully concluded the November $GTON staking event. Participants maintained their tokens on game balances and earned rewards like gold coins and gattoboxes. The next staking begins on December 1st, with more information on rewards coming soon. Source: link @tonlines

ПретходнаСтраница 1 од 3Следна