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

Резултати

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

Пребарај: #evolution

当前筛选 #evolution清除筛选
Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40394 · 23.12.2025 г., 15:05

An elephant’s trunk 🐘 is an amazing example of evolutionary development 🧬. It is a combined nose and upper lip that lengthened as the elephant’s ancestors became taller and their tusks grew bigger. With its heavy head, it needed an easy way to reach the ground. @googlefactss#evolution

Hashtags

Душнила по вызову

@dooooshno · Post #1091 · 23.07.2024 г., 10:19

Автопортреты Joni Mitchell, которые стали обложками её релизов • Clouds • Ladies Of The Canyon • Wild Things Run Fast • Turbulent Indigo • Taming The Tiger • Both Sides Now • Travelogue • Dreamland • The Reprise Albums (1968-1971) Митчелл часто говорила, что она «художник, который выпускает песни». Нельзя не заметить очевидную отсылку на другого художника, который за жизнь нарисовал с десяток автопортретов, — Винсента Ван Гога с отрезанным ухом на обложке «Turbulent Indigo». #evolution

Hashtags

Amazing Geography 🌍

@amazingeo · Post #402 · 22.10.2025 г., 12:31

🌍 The island of New Caledonia is a biodiversity hotspot where ancient plants like the rare Amborella tree represent some of Earth’s oldest surviving flowering lineages, found nowhere else. ✨ #biodiversity⚡#islands⚡#evolution⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #539 · 11.08.2025 г., 03:22

🌎 The star-nosed mole detects prey in total darkness using its unique nose, covered in 22 finger-like tentacles packed with touch sensors. This extraordinary adaptation lets it identify and eat tiny insects and worms faster than any other mammal, even underwater. ✨ #animals⚡#adaptation⚡#evolution 👉subscribe Interesting Planet

Interesting Planet 🌍

@interesting_planet_facts · Post #1146 · 20.12.2025 г., 12:11

🌎 The saiga antelope’s enlarged, drooping nose acts as a built-in air filter and cooler on the Central Asian steppes. When alarmed, herds can stampede at speeds up to 80 kilometers per hour. ✨ #animals⚡#evolution⚡#biodiversity 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1019 · 09.11.2025 г., 18:11

🌎 The shoebill stork stands over 1.2 meters tall and has a massive, shoe-shaped bill up to 24 centimeters long. Native to East African swamps, this solitary bird hunts lungfish, frogs, and even baby crocodiles. ✨ #animals⚡#biodiversity⚡#evolution 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #532 · 10.08.2025 г., 03:22

🌎 The platypus baffles scientists as it lays eggs like a reptile but produces milk and has fur like a mammal—a rare mix found in no other living animal. This odd, Australian creature even senses prey underwater using electroreceptors in its bill. ✨ #animals⚡#evolution⚡#Australia 👉subscribe Interesting Planet

Interesting Planet 🌍

@interesting_planet_facts · Post #1361 · 02.04.2026 г., 12:11

🌎 Horseshoe crabs have remained virtually unchanged for about 450 million years. Despite their name, they are more closely related to spiders than to true crabs. Modern horseshoe crabs can be found along the Atlantic coast of North America and in Southeast Asia. ✨ #animals⚡#evolution⚡#fossils 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #924 · 17.10.2025 г., 15:11

🌎 Living fossils like the chambered nautilus and horseshoe crab have changed little for hundreds of millions of years. The nautilus dates back over 500 million years, and its closest extinct relatives include ammonites, which died out with the dinosaurs. ✨ #evolution⚡#fossils⚡#animals 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #855 · 03.10.2025 г., 22:11

🌎 Living fossils like the giant freshwater stingray and the Australian lungfish have remained almost unchanged for over 100 million years, surviving dramatic changes in Earth’s environment. The horseshoe crab’s body plan is so ancient, it first appeared 450 million years ago. ✨ #evolution⚡#fossils⚡#animals 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #726 · 11.09.2025 г., 00:22

🌎 Some ancient animals have survived unchanged for millions of years. The coelacanth, once thought extinct, first appeared 400 million years ago and still swims deep ocean waters today. The horseshoe crab dates back over 450 million years, predating dinosaurs and even trees. ✨ #evolution⚡#fossils⚡#animals 👉subscribe Interesting Planet ​

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