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

Резултати

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

Пребарај: #gattoverse

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

@tonlines · Post #7240 · 16.05.2025 г., 13:37

Gatto Official Channel: Weekend Tournament Begins #GattoVerse#TON The GattoVerse Weekend Tournament kicks off, offering players the chance to win extraordinary prizes, including TON and various resources. The tournament starts on May 16 and ends on May 19. Participants are encouraged to join PvP battles and climb the leaderboard to secure top spots. Source: link @tonlines

TONlines – News

@tonlines · Post #6757 · 14.04.2025 г., 14:29

⚡️Gatto Official Channel: Dive into the GattoVerse NFT Adventure! #GattoVerse#TON GattoVerse welcomes the legendary NFT collection The Doge Pound with a trading volume of over $50,000,000. Join the event "Who let the dogs out?" and obtain new pets by purchasing Diamond Paws, which will transform into unique collectibles in two weeks. Source: link @tonlines

TONlines – News

@tonlines · Post #7186 · 13.05.2025 г., 09:04

⚡️Gatto Channel: Exciting Rewards with Lord Diamondog #GTON#GattoVerse Lord Diamondog has brought silver coins for $GTON, allowing players to purchase them and receive special rewards from the Hat Mouse Shop. Key prizes include treasury gold, spells, and resources for the future Lords of the GattoVerse, with bonus advantages for premium ticket holders. Source: link @tonlines

TONlines – News

@tonlines · Post #7025 · 02.05.2025 г., 13:32

Gatto | Official Channel: Battle in the GattoVerse #GattoVerse#GTON Gatto | Official Channel announces an exciting Weekend Tournament in the GattoVerse. Participants can win marvelous gifts, including various eggs, gold coins, and exclusive Gattoboxes. The tournament starts today and ends on May 5, with a special raffle using Crocottery Tickets. Source: link @tonlines

TONlines – News

@tonlines · Post #7138 · 09.05.2025 г., 12:38

Gatto | Official Channel (18+): Weekend Tournament Details #GattoVerse#Tournament GattoVerse is hosting a high-stakes Weekend Tournament starting today and ending on May 12. Participants in the PvP battles for $GTON can win prizes, including gold coins and exclusive Gattoboxes. Source: link @tonlines

TONlines – News

@tonlines · Post #6875 · 21.04.2025 г., 11:30

Gatto | Official Channel: A New Chapter with Nessie #Nessie#GattoVerse The GattoVerse was once again visited by Nessie, revealed not to be a monster but a protective mother of her species. After hatching her offspring, Nessie passed the responsibility of their care to the event participants who achieved 1000 damage points, rewarding them through the league. Source: link @tonlines

TONlines – News

@tonlines · Post #6766 · 14.04.2025 г., 18:36

Gatto: Upcoming Mine Rescheduling Announcement #Aetherian#GattoVerse Gatto | Official Channel announces a rescheduling of the mine due to a portal opening in the Aetherian world. The next mine event, offering two opportunities with rewards, is scheduled for April 24th. Source: link @tonlines

TONlines – News

@tonlines · Post #6743 · 13.04.2025 г., 18:08

⚡️GattoVerse: A Star Marks a New Beginning #GattoVerse#Aetherian The GattoVerse is on the brink of transformation as a new star promises to illuminate the skies, potentially creating a portal to the ancient Aetherian world. This event could turn legendary tales into reality, and merchant Hat Mouse is poised to seize the moment. Source: link @tonlines