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

Резултати

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

Пребарај: #weirdfacts

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

@googlefactss · Post #40061 · 10.11.2025 г., 19:02

Chanel Tapper holds the Guinness World Record for the longest tongue — 3.8 in (9.75 cm) — and says she loves watching people shriek in disbelief. She can remove Jenga blocks, grab a lemon from a glass, flip plastic cups, lift a spoon by curling it, and touch her nose and chin with the tip. [Read more] 👅✨😲 @googlefactss#weirdfacts#worldrecords#humanbody#nowyouknow#funfact

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40863 · 26.03.2026 г., 23:01

There is a naturally occurring metal called gallium that melts in your hand. It has a melting point of about 29.8°C (85.6°F), so just holding it makes it turn from a shiny solid into a silvery liquid. Gallium doesn’t react with air, so it can sit in your hand safely, but it can melt containers made of aluminum. Scientists use gallium in electronics, LED lights, and solar panels because of its unique properties. [Read more] @googlefactss #Science#WeirdFacts#Chemistry#DidYouKnow#Materials#Innovation

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40862 · 26.03.2026 г., 15:02

In Death Valley’s Racetrack Playa, large rocks, some weighing hundreds of kilograms, move across the dry lake bed, leaving long tracks behind. This happens when a rare set of conditions align. First, rain fills the lake bed with a shallow layer of water. At night, the water freezes into thin sheets of ice. As the sun warms the ground, the ice breaks into large, floating panels. Light winds then push the ice, slowly moving the rocks across the playa. The tracks left behind can last for decades, creating unique patterns. This natural process has been understood by scientists and is one of the most fascinating geological phenomena. 🪨❄️🌞 [Read more] @googlefactss #Nature#WeirdFacts#Geography#DidYouKnow#Deserts#Science#Mystery

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40844 · 23.03.2026 г., 07:01

There is a volcano in Indonesia called Kawah Ijen that glows bright blue at night. The blue glow comes from burning sulfur gases that ignite as they escape from the crater. Miners work in the area collecting solidified sulfur, even though the fumes are toxic. The effect makes the crater look like a surreal, electric-blue river flowing through the volcano, attracting photographers and adventurers from around the world. 🌋🔵🔥 [Read more 1] [Read more 2] @googlefactss #Nature#WeirdFacts#Volcanoes#DidYouKnow#Science#Adventure#Indonesia

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40821 · 18.03.2026 г., 15:03

There is a place in the Sahara Desert called the Richat Structure, also known as the “Eye of the Sahara.” It is a giant circular formation nearly 50 kilometers wide, visible from space. Scientists believe it formed from erosion, exposing layers of rock in concentric rings. The structure is perfectly round, which makes it look like a massive bullseye in the desert. It has fascinated explorers and geologists for decades because of its unusual shape. 🎯🏜️🌍 [Read more] @googlefactss #Geography#WeirdFacts#Nature#DidYouKnow#Desert#Earth#Landmarks

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40830 · 19.03.2026 г., 15:10

Mammatus clouds look like a sky full of hanging pouches or bubbles. Their name comes from the Latin word “mamma,” which means “breast,” because of their rounded, pouch-like shapes. These clouds often appear after thunderstorms and can be bright white, gray, or even orange during sunset. Despite their dramatic appearance, they are mostly harmless and form when cold air sinks into warmer air below, creating the pouch-like shapes. ☁️🌅🌩️ [Read more 1] [Read more 2] Show your own mammatus cloud pictures, the one with the most likes gets added to the post. 😉 @googlefactss #Nature#WeirdFacts#Weather#DidYouKnow#Clouds#Atmosphere#Sky