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

Пребарај: #habitability

当前筛选 #habitability清除筛选
Universe Mysteries 🪐

@cosmomyst · Post #81 · 04.08.2025 г., 20:11

🪐 The exoplanet Kepler-438b, orbiting a red dwarf star about 470 light-years from Earth, is one of the most Earth-like worlds found in terms of size and temperature. Scientists have carefully measured its position in the “habitable zone”—the region around a star where liquid water might exist, a key ingredient scientists believe is necessary for life as we know it. ✨ #aliens⚡#exoplanets⚡#habitability⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries

Universe Mysteries 🪐

@cosmomyst · Post #421 · 14.10.2025 г., 12:21

🪐 Astronomers have pinpointed the exoplanet LP 890-9 c, located about 105 light-years away in the constellation Eridanus, as one of the most promising places for life outside our solar system. This rocky world orbits within its star’s habitable zone—the region where temperatures could allow liquid water to persist, making it a key target in the search for planets that might support life as we know it. ✨ #exoplanets⚡#habitability⚡#astrobiology⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #509 · 20.11.2025 г., 12:21

🪐 Astronomers have discovered that the exoplanet Gliese 486 b, about 26 light-years away in the constellation Virgo, is a rocky world with surface temperatures hot enough to melt lead. Even though it's likely too warm for life as we know it, its firm, Earth-like surface and relatively close distance make it an important candidate for studying rocky planets outside our solar system—and for searching how and where life might survive under extreme conditions. ✨ #exoplanets⚡#life⚡#habitability⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #140 · 16.08.2025 г., 03:11

🪐 Around the distant red dwarf star LHS 1140, about 49 light-years from Earth, astronomers have discovered a rocky exoplanet called LHS 1140 b that sits right in the star’s “habitable zone”—the area where temperatures could allow liquid water to exist. Recent observations suggest its atmosphere may still be intact, making LHS 1140 b one of the most promising known worlds for the search for life beyond our solar system. ✨ #exoplanets⚡#habitability⚡#discovery⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries

Universe Mysteries 🪐

@cosmomyst · Post #171 · 22.08.2025 г., 13:11

🪐 Beyond our solar system, two intriguing exoplanets orbit the star Kepler-62: Kepler-62e and Kepler-62f. Both are considered "super-Earths" (planets larger than Earth but smaller than Neptune) and sit inside their star’s habitable zone, a region where temperatures might allow water to exist as a liquid—a key ingredient for life as we know it. ✨ #exoplanets⚡#habitability⚡#water⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries

Universe Mysteries 🪐

@cosmomyst · Post #129 · 14.08.2025 г., 00:11

🪐 Orbiting the cool red dwarf star Ross 128, about 11 light-years away, the exoplanet Ross 128 b is roughly Earth-sized and lies in its star’s temperate zone, where conditions might allow liquid water. Although Ross 128 is much dimmer than the Sun, its calm nature means less intense flares, making Ross 128 b an especially intriguing place in our search for potentially habitable worlds beyond our solar system. ✨ #exoplanets⚡#habitability⚡#water⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries

Universe Mysteries 🪐

@cosmomyst · Post #224 · 05.09.2025 г., 00:11

🪐 Astronomers have identified Kepler-442b, an exoplanet about 1,200 light-years away in the constellation Lyra, as a strong candidate for hosting life. This rocky world orbits in its star’s habitable zone—a region where temperatures could allow liquid water—and is just slightly larger than Earth, making it an intriguing example of a real planet with conditions that might one day support living organisms. ✨ #exoplanets⚡#habitability⚡#Kepler442b⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries ​

Universe Mysteries 🪐

@cosmomyst · Post #159 · 20.08.2025 г., 00:11

🪐 Scientists have identified the exoplanet Gliese 581d, orbiting a red dwarf star about 20 light-years away, as one of the earliest potentially habitable worlds outside our solar system. Gliese 581d lies within its star's habitable zone, where temperatures might allow liquid water to exist, making it a key target in the search for life beyond Earth. ✨ #exoplanet⚡#habitability⚡#water⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries

Universe Mysteries 🪐

@cosmomyst · Post #65 · 02.08.2025 г., 13:12

🪐 Just 39 light-years away, the exoplanet TRAPPIST-1e circles its cool red dwarf star in the habitable zone, where temperatures might allow liquid water. Scientists have found that TRAPPIST-1e has a rocky surface and, unlike some of its neighbors, could have the right conditions for life as we know it. ✨ #exoplanet⚡#habitability⚡#TRAPPIST1e⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries

Universe Mysteries 🪐

@cosmomyst · Post #83 · 05.08.2025 г., 03:11

🪐 Saturn’s moon Titan is one of the most intriguing places in the solar system where life could exist because it has lakes and rivers of liquid methane and ethane—chemicals similar to gasoline on Earth. While it’s far too cold for liquid water, scientists are captivated by the idea that life, if it ever formed there, would be fundamentally different from anything on our planet. ✨ #Titan⚡#methane⚡#habitability⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries

Universe Mysteries 🪐

@cosmomyst · Post #744 · 17.04.2026 г., 22:21

🪐 Astronomers have found signs that Uranus’s moon Miranda may hide a subsurface ocean of liquid water beneath its fractured, icy crust. The unique patterns of ridges and canyons on Miranda, revealed by Voyager 2, suggest internal heat could provide the conditions needed for liquid water—a key ingredient for life—even on this tiny, distant world. ✨ #Miranda⚡#oceanworlds⚡#habitability⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​