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

Резултати

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

Пребарај: #caves

当前筛选 #caves清除筛选
Interesting Planet 🌍

@interesting_planet_facts · Post #1376 · 17.04.2026 г., 12:11

🌎 In Slovenia, the Postojna Cave harbors a rare blind amphibian called the olm, which can live without food for up to 10 years. The cave stretches over 24 kilometers and contains vast chambers, underground rivers, and prehistoric animal remains. ✨ #geology⚡#caves⚡#biodiversity 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1167 · 26.12.2025 г., 22:11

🌎 Beneath Borneo’s limestone hills, the Clearwater Cave system spans over 237 kilometers, making it one of the world’s largest interconnected cave networks. Its underground river flows for 11 kilometers, supporting unique species like blind catfish and swiftlets that nest in its dark chambers. ✨ #caves⚡#geology⚡#biodiversity 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1080 · 28.11.2025 г., 12:11

🌎 The world’s deepest cave, Veryovkina Cave in Georgia, plunges to 2,212 meters below the surface. Its vertical shafts, tight squeezes, and frigid underground streams challenge expert cavers. Specially adapted crustaceans and fungi live in total darkness at these extreme depths. ✨ #caves⚡#geology⚡#biodiversity 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #704 · 07.09.2025 г., 13:22

🌎 In Croatia’s Velebit Mountains, the Lukina Jama–Trojama cave system plunges over 1,431 meters deep, housing rare leech species and tiny amphipods. Exploring these deep caves requires specialized rope techniques and careful study of underground water flows, revealing new life forms adapted to total darkness and isolation. ✨ #caves⚡#biodiversity⚡#geology 👉subscribe Interesting Planet ​

Interesting Planet 🌍

@interesting_planet_facts · Post #669 · 01.09.2025 г., 16:22

🌎 Deep beneath Venezuela, the Cueva del Fantasma cave is so massive that helicopters can fly inside. These vast underground chambers shelter unique bats, insects, and even entire ecosystems far from sunlight. ✨ #caves⚡#geology⚡#biodiversity 👉subscribe Interesting Planet ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1288 · 12.02.2026 г., 12:11

🌎 The world’s largest crystal cave, Cueva de los Cristales in Mexico, holds giant selenite crystals that measure up to 12 meters long. These crystals formed over 500,000 years in intense heat and humidity more than 300 meters below the surface. ✨ #minerals⚡#geology⚡#caves 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1139 · 17.12.2025 г., 22:11

🌎 Deep inside Lechuguilla Cave in New Mexico, explorers have found rare mineral formations called "subaqueous helictites." These twisted crystals form underwater from mineral-rich drips, creating shapes never seen elsewhere. The cave stretches over 248 kilometers, making it one of the longest surveyed caves in the world. ✨ #geology⚡#caves⚡#minerals 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #556 · 14.08.2025 г., 00:22

🌎 Deep within Mexico’s Cave of Swallows, birds plunge over 370 meters in freefall—a vertical drop so vast, entire skyscrapers could fit inside. This limestone sinkhole is among the world’s largest cave shafts, showcasing nature’s dramatic underground architecture. ✨ #geology⚡#birds⚡#caves 👉subscribe Interesting Planet

Interesting Planet 🌍

@interesting_planet_facts · Post #535 · 10.08.2025 г., 16:22

🌎 Salt crystals can form “cave chandeliers” in arid underground lakes. These sparkling formations grow when salty water evaporates, leaving dazzling, fragile mineral structures hanging from cave ceilings. ✨ #geology⚡#caves⚡#minerals 👉subscribe Interesting Planet

Interesting Planet 🌍

@interesting_planet_facts · Post #1009 · 06.11.2025 г., 12:11

🌎 Hidden deep beneath the Yucatán Peninsula in Mexico, the Sistema Sac Actun is the world’s longest underwater cave system. Stretching over 370 kilometers, these flooded limestone tunnels were formed by rainwater dissolving rock over thousands of years. Archaeologists have found ancient human and animal fossils preserved in the caves, including remains over 13,000 years old. ✨ #caves⚡#archaeology⚡#fossils 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #771 · 18.09.2025 г., 00:22

🌎 Deep inside Mexico’s Naica Mine, giant crystals of gypsum grow in the Cave of the Crystals, reaching up to 11 meters long. The cave’s extreme heat—up to 58°C—and high humidity make exploration challenging, and the crystals formed over at least 500,000 years in mineral-rich underground water. ✨ #caves⚡#crystals⚡#geology 👉subscribe Interesting Planet ​

Amazing Geography 🌍

@amazingeo · Post #577 · 15.01.2026 г., 12:31

🌍 Slovenia’s Škocjan Caves feature an underground canyon over 100 meters deep—the largest in Europe. This karst wonder drains rivers directly from the surface into vast hidden chambers. ✨ #caves⚡#karst⚡#geology⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

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