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

Резултати

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

Пребарај: #galaxycluster

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

@cosmomyst · Post #672 · 10.02.2026 г., 22:21

🪐 The galaxy cluster CLASH J0152.7-1357, observed by both Hubble and ground-based telescopes, contains vast amounts of dark matter—an invisible substance revealed only by its powerful gravitational pull on galaxies and hot gas. Despite being undetectable by any normal telescope, dark matter outweighs the visible content in CLASH J0152.7-1357, shaping the cluster and allowing scientists to map where this mysterious material gathers in the cosmos. ✨ #darkmatter⚡#galaxycluster⚡#cosmos⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #528 · 29.11.2025 г., 22:21

🪐 The galaxy cluster MACS J0416.1-2403 is held together by enormous amounts of dark matter—an invisible substance that does not emit or reflect light, but adds enough gravity to bind thousands of galaxies and clouds of hot gas. Observations show that the visible matter in MACS J0416.1-2403 makes up only a small fraction of the total mass, highlighting how most of the cluster’s true weight comes from this mysterious, unseen ingredient shaping the universe on the largest scales. ✨ #darkmatter⚡#galaxycluster⚡#mysteries⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #130 · 14.08.2025 г., 03:11

🪐 The galaxy cluster CL0024+17, located about 5 billion light-years away, has helped scientists visualize dark matter using a phenomenon called gravitational lensing—where the cluster's gravity bends the light from even more distant galaxies and creates giant arcs in the sky. This invisible "scaffolding" of dark matter shapes the cluster's structure and reveals mysterious regions that emit no light but hold enormous mass, showing the universe is built on something we still cannot see. ✨ #darkmatter⚡#galaxycluster⚡#mysteries⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries

Universe Mysteries 🪐

@cosmomyst · Post #302 · 20.09.2025 г., 15:21

🪐 In the galaxy cluster El Gordo, astronomers have observed evidence that most of its mass is not from visible matter but from dark matter—a mysterious, invisible substance that outweighs all the galaxies and gas combined. Detailed gravitational lensing (where gravity bends and magnifies the light from more distant galaxies) reveals vast, hidden regions in El Gordo, confirming that dark matter acts as a cosmic glue, binding this colossal cluster together and shaping its structure on a grand scale. ✨ #darkmatter⚡#lensing⚡#galaxycluster⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries ​

Universe Mysteries 🪐

@cosmomyst · Post #604 · 05.01.2026 г., 22:21

🪐 Scientists studying the distant galaxy cluster MACS J1149+2223 use it as a window into the fate of the cosmos, tracking how the accelerated expansion driven by dark energy might eventually push galaxies so far apart that their light can never reach each other again. Over unimaginable timescales, clusters like MACS J1149+2223 will fade from view as the universe expands, leaving behind only a cold, dark emptiness—an ending known as "cosmic isolation" that awaits even the brightest galaxies. ✨ #universe⚡#expansion⚡#darkenergy⚡#galaxycluster⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #175 · 23.08.2025 г., 00:11

🪐 Within the distant galaxy cluster MACS J1423.8+2404, astronomers have measured the effects of dark energy—a mysterious force causing the universe to expand faster and faster over time. By studying how galaxies in this cluster are drifting apart, scientists collect real-world evidence that dark energy acts like a kind of "anti-gravity," pushing the vast cosmic web ever outward and shaping the fate of everything we see in the universe. ✨ #darkenergy⚡#galaxycluster⚡#expansion⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries ​

Universe Mysteries 🪐

@cosmomyst · Post #269 · 14.09.2025 г., 03:11

🪐 In the galaxy cluster Abell 3827, astronomers have observed four galaxies merging and spotted what may be the first hints that dark matter—an invisible substance shaping the cosmos—can interact with itself beyond just gravity. By watching how dark matter halos (the unseen envelopes around galaxies) seem to lag behind their stars during the collision, scientists are piecing together clues about this mysterious material that outweighs all ordinary matter in the universe. ✨ #darkmatter⚡#abell3827⚡#galaxycluster⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries ​