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

Резултати

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

Пребарај: #longevity

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

@interesting_planet_facts · Post #498 · 04.08.2025 г., 16:22

🌎 The planet’s oldest living animal is the deep-sea quahog clam. One specimen, named Ming, lived to be 507 years old before being discovered near Iceland. ✨ #ocean⚡#longevity⚡#animals 👉subscribe Interesting Planet

Amazing Geography 🌍

@amazingeo · Post #500 · 07.12.2025 г., 20:31

🌍 Some of the world’s oldest lakes, like Lake Ohrid in Europe, have existed for more than one million years, preserving unique species found nowhere else on Earth. ✨ #lakes⚡#biodiversity⚡#longevity⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #376 · 21.07.2025 г., 16:22

🌎 In the Himalayan foothills, the Kalpavriksha, or “tree of heaven,” is a fig tree revered for living over 2,500 years. Its resilient roots stabilize soil and support hundreds of animal species, making it both a cultural icon and a pillar of its ecosystem. ✨ #botany⚡#longevity⚡#wildlife 👉subscribe Interesting Planet

Interesting Planet 🌍

@interesting_planet_facts · Post #948 · 22.10.2025 г., 12:11

🌎 The Welwitschia mirabilis, found only in the Namib Desert of Namibia and Angola, survives on coastal fog and can live over 1,500 years. Its two long leaves grow continuously, shredding into ribbons that cover the sand around the plant. ✨ #botany⚡#desert⚡#longevity 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #413 · 25.07.2025 г., 03:22

🌎 In Namibia, the welwitschia mirabilis plant survives for over 1,000 years with just two leaves! These tough leaves grow nonstop, curling and splitting in the harsh desert. ✨ #botany⚡#desert⚡#longevity 👉subscribe Interesting Planet

Interesting Planet 🌍

@interesting_planet_facts · Post #1186 · 02.01.2026 г., 22:11

🌎 Giant tortoises from the Galápagos and Aldabra islands are true living fossils. Their ancestors appeared over 40 million years ago, and some individuals today can live more than 150 years. ✨ #evolution⚡#reptiles⚡#longevity 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #470 · 30.07.2025 г., 20:22

🌎 High in the Andes, the Yareta plant forms cushion-like mounds that can live for over 3,000 years. Its dense, bright-green surface helps conserve heat, allowing it to survive freezing mountain nights. ✨ #plants⚡#longevity⚡#mountains 👉subscribe Interesting Planet

Interesting Planet 🌍

@interesting_planet_facts · Post #397 · 23.07.2025 г., 17:22

🌎 The Pando aspen grove in Utah is a single living organism made up of 47,000 genetically identical trees, all connected by one massive underground root system. This silent giant is considered one of the world’s largest and oldest living things, possibly dating back 14,000 years. ✨ #trees⚡#biology⚡#longevity 👉subscribe Interesting Planet

Interesting Planet 🌍

@interesting_planet_facts · Post #612 · 23.08.2025 г., 00:22

🌎 The Californian coastal redwoods are the tallest living trees on Earth, soaring over 115 meters high. Their thick bark and tannins protect them from fire and insects, letting these giants live for thousands of years. ✨ #trees⚡#forest⚡#longevity 👉subscribe Interesting Planet ​

Venture Village Wall 🦄

@venturevillagewall · Post #3638 · 21.12.2024 г., 10:23

Jrnys Secures $8.65M Funding Jrnys has raised $8.65 million to enhance personalized healthcare focused on weight loss solutions using GLP-1s like Zepbound, Mounjaro, Ozempic, and Wegovy. The company also addresses Sexual Wellness, Haircare, and Longevity needs. #Funding#Healthcare#WeightLoss#GLP1#Zepbound#Mounjaro#Ozempic#Wegovy#SexualWellness#Haircare#Longevity

Venture Village Wall 🦄

@venturevillagewall · Post #3678 · 23.12.2024 г., 18:00

DeSci Gains Momentum Amid Innovation Decentralized science (DeSci) is gaining traction with recent developments: 1️⃣Bio Protocol joins Binance Launchpool as the 69th project, focusing on decentralized science token launches. So far, 7 projects have raised $23M, with $7M allocated for research. More info here. 2️⃣Pump.science launches, allowing community-driven scientific experiments, starting with a longevity project. Their collaboration with Pulse will use health data metrics for future experiments. Learn more about Pump.science. 3️⃣ The Sci-Hub token has been introduced on pump.fun, providing access to scientific papers; the founder promotes purchasing the token to support open science. Token details here and Sci-Hub info here. While still niche compared to AI and meme coins, DeSci is attracting interest, paving the way for wider community involvement. Let's observe how DeSci progresses into 2025! #DeSci#BioProtocol#Binance#PumpScience#SciHub#Token#Research#Innovation#Web3#Community#HealthTech#Crypto#Launch#Investment#Experimentation#Longevity#OpenScience#Funding#Technology#Blockchain#Ethereum