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 слични објави

Пребарај: #extremes

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

@interesting_planet_facts · Post #368 · 20.07.2025 г., 18:22

🌎 The deepest point on land is the Bentley Subglacial Trench in Antarctica, buried beneath almost 3 kilometers of ice. This hidden valley lies 2,555 meters below sea level, far deeper than Death Valley, and remains inaccessible except through advanced radar technology. ✨ #Antarctica⚡#geology⚡#extremes 👉subscribe Interesting Planet

Amazing Geography 🌍

@amazingeo · Post #315 · 30.09.2025 г., 15:31

🌍 The Gobi Desert experiences freezing winters with temperatures dropping below –40°C, making it one of the few deserts known for both scorching heat and extreme cold. ✨ #deserts⚡#climate⚡#extremes⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #755 · 15.09.2025 г., 16:22

🌎 High-altitude deserts like the Atacama in Chile are among Earth’s driest extreme climate zones, receiving less than 2 millimeters of rain a year. These parched regions are so arid that some weather stations have never recorded rainfall. ✨ #climate⚡#desert⚡#extremes 👉subscribe Interesting Planet ​

Amazing Geography 🌍

@amazingeo · Post #694 · 18.04.2026 г., 20:31

🌍 Antarctica’s interior is the only place on Earth with a true polar climate—temperatures rarely rise above freezing, and less precipitation falls each year than in most deserts. ✨ #climatezones⚡#antarctica⚡#extremes⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #58 · 16.08.2025 г., 09:12

🌍 Earth holds the record for the highest known surface temperatures for a rocky planet in our Solar System, with some desert spots topping 56°C—hotter than the ground on Venus or Mars. ✨ #planet⚡#deserts⚡#extremes⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍

Interesting Planet 🌍

@interesting_planet_facts · Post #1102 · 05.12.2025 г., 18:11

🌎 Rising in the Peruvian Andes at 5,100 meters, La Rinconada is the world’s highest permanent settlement. Over 40,000 people live here, mostly mining gold in challenging conditions with no running water or sewage system. ✨ #settlements⚡#geography⚡#extremes 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1357 · 30.03.2026 г., 12:11

🌎 Life thrives in Earth’s extreme climate zones, like the frigid polar regions and the hyper-arid Atacama Desert. The Atacama receives less than 2 mm of rain annually, making it one of the driest places on Earth, while Antarctica sees winter temperatures plunge below –60°C. ✨ #climate⚡#extremes⚡#geography⚡#adaptation 👉subscribe Interesting Planet 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #161 · 02.09.2025 г., 09:12

🌍 The Lut Desert in Iran holds the record for Earth’s hottest land temperature ever measured from space—an astonishing 80.8°C, far exceeding typical desert heat. ✨ #deserts⚡#temperature⚡#extremes⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍 ​

Universe Mysteries 🪐

@cosmomyst · Post #17 · 29.07.2025 г., 21:00

🪐 In 2016, astronomers using the Hubble Space Telescope observed the exoplanet WASP-121b, where temperatures in its stratosphere soar above 2,500°C and molecules such as water vapor exist as glowing, superheated gas. The planet’s intense gravity causes it to stretch into a teardrop shape, while metals like iron and magnesium escape its atmosphere, streaming into space in a shimmering trail. ✨ #exoplanets⚡#atmosphere⚡#extremes 👉subscribe Universe Mysteries

Interesting Planet 🌍

@interesting_planet_facts · Post #723 · 10.09.2025 г., 16:22

🌎 The coldest permanently inhabited place is Oymyakon, Russia, where winter temperatures drop below −50°C. The hottest surface temperature recorded was 80.8°C in Iran’s Lut Desert in 2005. ✨ #climate⚡#extremes⚡#Earth⚡#geography 👉subscribe Interesting Planet ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1131 · 15.12.2025 г., 12:11

🌎 Nestled in the Siberian taiga, the Russian town of Verkhoyansk is one of the coldest inhabited places on Earth. Winter temperatures can drop below –50°C, and the town recorded a range of over 105°C between its lowest and highest temperatures—a world record for temperature variation in a single settlement. ✨ #cities⚡#Siberia⚡#extremes 👉subscribe Interesting Planet 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #546 · 08.12.2025 г., 22:21

🪐 Exoplanet 2MASS J2126–8140 holds the record for the widest known orbit around its star—about 1 trillion kilometers away, or nearly 7,000 times the distance from Earth to the Sun. This gas giant drifts so far from its host that a single "year" there lasts nearly 900,000 Earth years, exposing it to the coldest, loneliest planetary conditions ever measured. ✨ #exoplanets⚡#extremes⚡#space⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos 👉subscribe Universe Mysteries 👉more Channels ​

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