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

Резултати

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

Пребарај: #romantasy

当前筛选 #romantasy清除筛选
Velvet Pages | eLibrary 🥂

@bookslibraryofficial · Post #1268 · 18.05.2025 г., 16:31

📖Title : Fearless ✍️Author : Lauren Roberts ⭐️Rating : 4.22/5 (Goodreads) 📆Published : Apr 08, 2025 ———————————————— Summary:Fearless by Lauren Roberts is the gripping conclusion to The Powerless Trilogy, a young adult romantasy series. The story follows Paedyn Gray, an Ordinary in a world dominated by the powerful Elites, as she returns to the Kingdom of Ilya. Facing a life-altering decision, Paedyn must navigate political intrigue, personal betrayals, and the complexities of love. Her relationship with Kai Azer, an Elite and her former adversary, intensifies amidst the kingdom's turmoil. As Paedyn confronts trials that test her courage and resilience, she challenges societal norms and redefines strength. Roberts weaves a tale of empowerment, loyalty, and the enduring power of love in a fractured world. ———————————————— #fiction#fantasy#romantasy#youngadult@Bookslibraryofficial@free_novellas@the_ancient_library

Velvet Pages | eLibrary 🥂

@bookslibraryofficial · Post #1264 · 18.05.2025 г., 06:46

📖Title : Enigma ✍️Author : RuNyx ⭐️Rating : 3.91/5 (Goodreads) 📆Published : Apr 29, 2025 ———————————————— Summary:Enigma by RuNyx is a steamy dark academia romance that follows Salem Salazar, the black sheep of a wealthy family, as she enters Mortimer University to uncover the truth behind her sister's mysterious death. Obsessed with death and driven by secrets, Salem is soon entangled with Cazimir van der Waal—a chaotic, brooding artist and teaching assistant with a hidden past. Their intense, rivals-to-lovers relationship unfolds amid secret societies, missing girls, and deadly mysteries on campus. As danger closes in, passion ignites between fire and ice. *Enigma* is a twisted, suspenseful tale of obsession, love, and peril set in an academic underworld. ———————————————— #fiction#darkromance#fantasy#romantasy#darkacademia@Bookslibraryofficial@free_novellas@the_ancient_library

Velvet Pages | eLibrary 🥂

@bookslibraryofficial · Post #1473 · 16.11.2025 г., 15:17

📖Title : Blackthorn ✍️Author : J.T. Geissinger ⭐️Rating : 4.03/5 (Goodreads) 📆Published : Nov 04, 2025 ———————————————— Summary:Blackthorn follows Maven Blackthorn as she returns to her haunted hometown after her grandmother’s funeral—only to discover the body has mysteriously vanished. Caught in a generations-old feud between the Blackthorns and the powerful Croft family, Maven is forced to confront Ronan Croft, her first love and the son of her mother’s suspected killer. Their dangerous chemistry resurfaces as whispers of occult rituals, buried secrets, and horrific betrayals emerge. As Maven digs deeper, she uncovers a terrifying truth that threatens everyone she loves. In a town where the dead refuse to rest, love becomes both a weapon and a deadly curse. ———————————————— #romance#gothic#romantasy#fantasy#paranormal@Bookslibraryofficial@free_novellas@eternalmantra