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

Пребарај: #fastbursts

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

@cosmomyst · Post #638 · 24.01.2026 г., 22:21

🪐 In the galaxy M81, located about 12 million light-years away, scientists have detected mysterious, isolated fast radio bursts—brief blasts of radio waves lasting just milliseconds but releasing as much energy as hundreds of millions of suns. These puzzling signals are so powerful and short-lived that pinpointing their exact origins within M81 has become a cosmic detective story, as astronomers use radio telescopes to track each fleeting flash from this nearby spiral galaxy. ✨ #fastbursts⚡#galaxies⚡#phenomena⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #325 · 24.09.2025 г., 22:21

🪐 In 2022, astronomers used the Hubble Space Telescope to identify a fast radio burst originating from a galaxy called WISEA J071634.59–190039.2, located about 6 billion light-years from Earth. This pinpointed location helps scientists study the environments where these ultra-short, powerful flashes of radio energy are born, revealing new clues about the mysterious origins of fast radio bursts across the cosmos. ✨ #fastbursts⚡#hubble⚡#galaxies⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #282 · 16.09.2025 г., 20:11

🪐 In the galaxy dubbed "The Whale" (NGC 4631), astronomers have detected a barrage of fast radio bursts—ultra-brief, intense flashes of radio energy—coming not from the center, but from the galaxy’s outer regions. These mysterious signals last just milliseconds but shine as brightly as billions of suns, making NGC 4631's outskirts a surprising hotspot for one of space’s most powerful, fleeting phenomena. ✨ #fastbursts⚡#galaxies⚡#radioastronomy⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries ​

Universe Mysteries 🪐

@cosmomyst · Post #235 · 07.09.2025 г., 03:11

🪐 In 2020, astronomers traced a fast radio burst called FRB 200428 to our own Milky Way and found it came from a magnetar named SGR 1935+2154. This was the first time a fast radio burst—a super-short flash of radio energy from space—was directly linked to a known type of object, showing that magnetars, which are neutron stars with extremely strong magnetic fields, can produce these intense cosmic signals. ✨ #fastbursts⚡#magnetars⚡#milkyway⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries ​

Universe Mysteries 🪐

@cosmomyst · Post #480 · 05.11.2025 г., 22:21

🪐 In 2023, astronomers using the Australian Square Kilometre Array Pathfinder (ASKAP) discovered a repeating fast radio burst called FRB 20220912A in the spiral galaxy ESO 601-G024, about 1 billion light-years away. Unlike other repeating bursts, FRB 20220912A's signal showed a strong "downward drift" in frequency, meaning each pulse slowly slid to lower radio frequencies over just a few milliseconds, helping scientists trace the physical processes at the burst's origin. ✨ #fastbursts⚡#radio⚡#spiralgalaxy⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #706 · 09.03.2026 г., 22:21

🪐 Among the strangest discoveries in astronomy are fast radio bursts (FRBs) emerging from the spiral galaxy NGC 253, also known as the Sculptor Galaxy. In 2022, scientists detected a repeating FRB source here—brief flashes of radio energy lasting just milliseconds and releasing more power than the Sun generates in years—making NGC 253 a new hot spot in the ongoing quest to understand these mysterious cosmic signals. ✨ #fastbursts⚡#sculptorgalaxy⚡#radioastronomy⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #556 · 13.12.2025 г., 22:21

🪐 In 2023, the Australian Square Kilometre Array Pathfinder detected an unusual pattern in fast radio bursts coming from the spiral galaxy NGC 2082, with several bursts arriving from different regions within the same galaxy. These millisecond flashes of radio energy, each releasing as much power as hundreds of millions of suns, show that multiple mysterious sources can exist in a single galaxy, deepening the puzzle of what causes these intense cosmic signals. ✨ #fastbursts⚡#ngc2082⚡#radioenergy⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​