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

Резултати

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

Пребарај: #redbook

当前筛选 #redbook清除筛选
EKOLOG.UZ| ENG

@ekologuzenglish · Post #11767 · 01.03.2026 г., 14:59

#RedBook🌷 Tulipa affinis (Relative Tulip) A rare endemic plant of the Western Pamir-Alay region, found only in limited areas. Its bright red flower with a black center and yellow border makes the plant especially striking — but this beauty is also one of the reasons it is often destroyed. 📍Distribution In Uzbekistan, it grows in the Jizzakh, Samarkand, and Navoi regions — on the Turkestan and Malguzar mountain ranges and in the Nurata Mountains. It is also found in Kyrgyzstan and Tajikistan. The plant grows on rocky slopes, in gorges, and among shrubs and juniper woodlands. 🌱Plant characteristics ▫️ Perennial bulbous plant, 15–25 cm tall ▫️ Blooms in April–May ▫️ Reproduces by seeds and vegetatively ▫️ Occurs rarely in nature — as single plants or small groups ⚠️Why the species is under threat The main reasons for the population decline are mass collection of flowers and livestock grazing, which destroy the plant’s natural habitat. 🌿Conservation status The plant has been cultivated in the Botanical Garden of the Academy of Sciences of the Republic of Uzbekistan since 1957 and is protected in Zaamin State Reserve and Nurata State Reserve. 💚 Protecting rare plants is an important part of preserving biodiversity. Take care of nature and do not pick wild flowers. ☘️Read the latest environmental news on the @ekologuz page. Follow us and send your suggestions and wishes via @eklguz_bot Instagram | Facebook | Twitter | Sayt | Youtube.

Hashtags

EKOLOG.UZ| ENG

@ekologuzenglish · Post #10738 · 12.12.2025 г., 01:04

📕#RedBook WILD GRAPEVINE Latin name: Vitis vinifera L. Status: Category 3 – Rare species with a fragmented range in Uzbekistan 🌿 Description A climbing woody vine reaching up to 30 meters in length. Leaves are simple, nearly round, 3–5-lobed or palmately divided, with a heart-shaped base; edges are serrated or crenate. The inflorescence is a dense or loose panicle. Fruits vary in color and shape. Flowers in May–June, fruits ripen in July–October. 📍 Distribution In Uzbekistan: – Jizzakh, Surkhandarya, Tashkent regions: ▪️ Nurata range (Gurdara and Bolosoy gorges) ▪️ Gissar range (Sangardak and Tupalang river basins) – Western Tien Shan: Pskem, Ugam, Korzhantau, Chatkal ranges Also found in: – Tajikistan – Kyrgyzstan – Kazakhstan 🌱 Habitat Grows along riverbanks, in gorges, on gravelly and fine-soil mountain slopes. 🔢 Population Occurs as solitary plants or in small clusters. ♻️ Reproduction Reproduces by seeds and vegetatively. ⚠️ Threats and Causes of Decline – Trampling and damage caused by grazing livestock – Use of the plant as firewood These factors lead to a steady reduction in population and habitat range. 🌿 Domestication and Importance Cultivated in all botanical gardens of Central Asia, in specialized horticultural research plots, and at breeding stations for developing new varieties. 🛡 Conservation Measures – Protected in the Nurata and Chatkal State Nature Reserves – Under protection in the Ugam–Chatkal National Park ☘️Read the latest environmental news on the @ekologuz page. Follow us and send your suggestions and wishes via @eklguz_bot Instagram | Facebook | Twitter | Sayt | Youtube.

Hashtags

EKOLOG.UZ| ENG

@ekologuzenglish · Post #11614 · 15.02.2026 г., 11:03

🦅 Peregrine Falcon — the fastest bird in the world The peregrine falcon can reach speeds of up to 390 km/h during a dive. These majestic predators hunt birds and small mammals, playing a vital role in maintaining the balance of ecosystems. ❗️ Important: the peregrine falcon is listed in the Red Book of Uzbekistan. Its population is under threat due to habitat destruction, poaching, and environmental pollution. 🌿 Protecting peregrine falcons is a contribution to preserving the biodiversity and future of our country’s nature. #PeregrineFalcon#RedBook#ProtectNature#RareBirds#Biodiversity ☘️ Follow the latest environmental news on @ekologuz. Subscribe and send your suggestions and feedback via @eklguz_bot