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

Резултати

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

Пребарај: #supernova

当前筛选 #supernova清除筛选
Space Universe🌌

@spaceuniverses · Post #147 · 26.02.2022 г., 16:00

💥The shock wave from the #supernova explosion that created remnant G306 is racing through #space at ~2.4 million km/h. Chandra data reveals iron, neon, silicon, and sulfur all at temperatures exceeding 28 million C. A reminder not only of the energies involved, but of the role supernovas play in seeding galaxies with heavy elements produced in the hearts of massive stars.🌟

Interesting Planet 🌍

@interesting_planet_facts · Post #911 · 15.10.2025 г., 12:11

🌎 In 2020, astronomers detected a mysterious object named “The Cow,” a fast and extremely bright stellar explosion. Unlike normal supernovas, “The Cow” rapidly peaked in brightness, confounding scientists. Follow-up observations revealed it was likely the birth of a black hole or neutron star—providing a rare view of a star’s collapse in real time. ✨ #astronomy⚡#supernova⚡#blackhole 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #512 · 06.08.2025 г., 20:22

🌎 Gold, a precious metal treasured since ancient times, forms in supernova explosions when massive stars die. This cosmic alchemy scatters gold atoms through space, seeding our planet with the gold we mine and wear today. ✨ #gold⚡#supernova⚡#astronomy 👉subscribe Interesting Planet

Universe Mysteries 🪐

@cosmomyst · Post #700 · 03.03.2026 г., 22:21

🪐 In 2016, astronomers watched the star KSN 2011d in the galaxy UGC 11066 explode as a supernova, capturing the "shock breakout"—a brief burst of light that occurs when the explosion’s blast wave first reaches the star’s surface. This rare observation let scientists directly witness the very instant a star’s core collapse triggers a cosmic explosion, providing clues to the exact sequence of events when massive stars end their lives and enrich their galaxies with newly created elements. ✨ #supernova⚡#stars⚡#galaxies⚡#nasa⚡#galaxy⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

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

🪐 In the distant galaxy MACS J1149+2223, astronomers have witnessed an unusual event called a "refreshed" supernova, where a massive star's explosion appeared to brighten twice, likely caused by material from the original blast catching up to the shockwave years later. This rare phenomenon allows scientists to observe the same supernova event evolving in real time, a cosmic encore not often seen in the universe. ✨ #supernova⚡#galaxy⚡#phenomena⚡#nasa⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries

Universe Mysteries 🪐

@cosmomyst · Post #681 · 15.02.2026 г., 12:21

🪐 In the spiral galaxy NGC 2525, located around 70 million light-years from Earth, astronomers watched supernova SN 2018gv gradually fade over 2018 and 2019 in real time. This stellar explosion outshone its entire galaxy for weeks—when a white dwarf star in a close binary system grew too heavy and detonated, releasing enough energy to briefly rival the brightness of billions of suns before slowly fading back into darkness. ✨ #supernova⚡#NGC2525⚡#astronomy⚡#nasa⚡#galaxy⚡#stars⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #586 · 28.12.2025 г., 12:21

🪐 The supernova SN 1987A in the Large Magellanic Cloud, about 168,000 light-years from Earth, stunned astronomers by producing a burst of neutrinos—ghostly particles that rarely interact with normal matter—detected in underground observatories worldwide. This was the first time scientists caught direct evidence that a supernova creates these elusive particles during a star's collapse, confirming key theories about how massive stars end their lives and spread elements throughout space. ✨ #supernova⚡#neutrinos⚡#stars⚡#nasa⚡#galaxy⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #199 · 27.08.2025 г., 20:11

🪐 Deep inside the galaxy 3C 273, astronomers have identified a quasar—a super-bright region powered by a supermassive black hole eating up material, causing it to shine with light brighter than entire galaxies. Meanwhile, the Crab Pulsar in the Crab Nebula is a rapidly spinning neutron star left over from a massive star’s explosion, sending out beams of radio waves and light as it spins—a cosmic lighthouse flashing 30 times a second. ✨ #quasars⚡#pulsars⚡#supernova⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries ​

Universe Mysteries 🪐

@cosmomyst · Post #225 · 05.09.2025 г., 03:11

🪐 In the vacuum of space, the speed of light is an incredible 299,792 kilometers per second—so fast that a beam from the Sun takes just over eight minutes to reach Earth, even though the distance is about 150 million kilometers. When astronomers observe events like a supernova in the galaxy NGC 2525, they're actually seeing what happened years, decades, or even millions of years ago, because the light takes that long to cross vast cosmic distances. ✨ #speedoflight⚡#space⚡#distances⚡#supernova⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos 👉subscribe Universe Mysteries ​

Universe Mysteries 🪐

@cosmomyst · Post #254 · 11.09.2025 г., 00:11

🪐 The magnetar CXOU J171405.7−381031, found in the supernova remnant CTB 37B, is famous for its exceptionally strong magnetic field—over a thousand trillion times more powerful than Earth's. Such intense magnetism can twist the star’s crust, causing violent starquakes and bursts of high-energy radiation that briefly outshine everything else in its region of space. ✨ #magnetar⚡#supernova⚡#neutronstar⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries ​

12
ПретходнаСтраница 1 од 2Следна