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

Резултати

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

Пребарај: #ecosystems

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

@interesting_planet_facts · Post #643 · 28.08.2025 г., 03:22

🌎 Entering the massive Krubera Cave in Georgia is like descending into another world—at over 2,197 meters deep, it’s the deepest known cave on Earth. These underground labyrinths feature rivers, waterfalls, and unique blind creatures, revealing entire ecosystems hidden from sunlight. ✨ #geology⚡#caves⚡#ecosystems 👉subscribe Interesting Planet ​

Interesting Planet 🌍

@interesting_planet_facts · Post #630 · 26.08.2025 г., 00:22

🌎 From blazing deserts to frozen poles, Earth's extreme climate zones push life to its limits. In polar regions, temperatures plunge below -50°C, creating icy landscapes where only the hardiest animals, like penguins and polar bears, survive. Meanwhile, equatorial deserts like the Sahara reach scorching highs over 50°C, supporting unique plants and animals adapted to relentless heat. These climate extremes shape our planet’s most remarkable ecosystems and inspire some of nature’s wildest survival strategies. ✨ #climate⚡#ecosystems⚡#adaptation 👉subscribe Interesting Planet ​

Amazing Geography 🌍

@amazingeo · Post #542 · 28.12.2025 г., 20:31

🌍 The Serengeti savanna in Africa hosts one of the world’s largest mammal migrations—zebras cross first, followed by wildebeest, each group timing their journey to feed on different heights of grass. ✨ #savanna⚡#migration⚡#ecosystems⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #583 · 20.01.2026 г., 20:31

🌍 Africa’s Miombo savanna covers over 2.7 million square kilometers—about the size of Argentina. Its woodlands support hundreds of unique butterfly species found nowhere else on Earth. ✨ #savanna⚡#grasslands⚡#ecosystems⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #927 · 17.10.2025 г., 22:11

🌎 Hidden off the Pacific coast of California, the Point Dume Submarine Canyon plunges over 800 meters deep just a short distance from shore. Scientists have discovered mysterious methane seeps and rare deep-sea corals within the canyon. These underwater features support unique ecosystems not found anywhere else nearby. ✨ #ocean⚡#canyon⚡#ecosystems 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #589 · 19.08.2025 г., 16:22

🌎 Some bamboo species can grow up to 91 centimeters in a single day, making bamboo one of the fastest-growing plants on Earth. This rapid growth helps bamboo quickly regenerate after being harvested and provides vital habitats for many animals. ✨ #botany⚡#speed⚡#ecosystems 👉subscribe Interesting Planet

Interesting Planet 🌍

@interesting_planet_facts · Post #484 · 02.08.2025 г., 03:22

🌎 Deep in the Congo Basin, the African rainforest elephant forges secret trails through dense jungle, creating “elephant highways” that other animals use. These hidden paths help shape entire forest ecosystems by opening routes for seed dispersal and wildlife movement. ✨ #rainforest⚡#elephants⚡#ecosystems 👉subscribe Interesting Planet

Amazing Geography 🌍

@amazingeo · Post #647 · 25.02.2026 г., 20:31

🌍 Submarine hydrothermal vents on the ocean floor release superheated water and minerals, fueling unique ecosystems powered by chemical energy instead of sunlight. ✨ #processes⚡#ocean⚡#ecosystems⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #466 · 30.07.2025 г., 13:22

🌎 In the dry canyons of the American Southwest, cryptobiotic soil forms a living crust of bacteria, fungi, and lichens. This fragile layer stabilizes desert soil and helps seeds germinate, supporting entire ecosystems in these harsh climates. ✨ #desert⚡#microbiology⚡#ecosystems 👉subscribe Interesting Planet

Amazing Geography 🌍

@amazingeo · Post #280 · 21.09.2025 г., 22:31

🌍 Some deep-water corals build reefs in cold, dark oceans thousands of meters below the surface. Unlike tropical reefs, these cold-water reefs thrive without sunlight or warm water. ✨ #coral⚡#marine⚡#ecosystems⚡#ocean⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍 ​

Amazing Geography 🌍

@amazingeo · Post #223 · 12.09.2025 г., 13:12

🌍 The highest forests on Earth grow above 4,900 meters in the Andes, where trees survive thin air, cold temperatures, and strong sunlight—an extreme zone where biosphere meets atmosphere and lithosphere. ✨ #spheres⚡#Andes⚡#ecosystems⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍 ​

Interesting Planet 🌍

@interesting_planet_facts · Post #619 · 24.08.2025 г., 03:22

🌎 The tuco-tuco, a South American rodent, lives almost its entire life underground. It digs vast tunnel networks with specialized teeth, rarely surfacing except to gather food. Its burrowing helps aerate soil, making tuco-tucos quiet but essential ecosystem engineers. ✨ #rodents⚡#ecosystems⚡#burrowing 👉subscribe Interesting Planet ​

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