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

Резултати

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

Пребарај: #jets

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

@cosmomyst · Post #693 · 24.02.2026 г., 22:21

🪐 In the star system V Hydrae, located about 1,300 light-years away in Hydra, astronomers have observed mysterious, high-speed "bullets" of hot gas being violently ejected from the dying red giant star. These jets blast out at speeds up to 800,000 kilometers per hour and appear at regular intervals, creating bizarre patterns of moving material that are among the strangest cosmic outflows seen in our galaxy. ✨ #phenomena⚡#stars⚡#jets⚡#nasa⚡#galaxy⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #197 · 27.08.2025 г., 13:11

🪐 In the heart of the Centaurus galaxy NGC 5128, the supermassive black hole devours gas and dust, releasing twin jets of particles that stretch for over a million light-years into space. These jets, visible in both radio and X-ray light, show how black holes can not only swallow matter but also launch some of the most powerful streams of energy in the universe, shaping entire galaxies far beyond their event horizons—the invisible boundaries from which nothing can return. ✨ #blackholes⚡#galaxies⚡#jets⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries ​

Universe Mysteries 🪐

@cosmomyst · Post #3 · 29.07.2025 г., 14:41

🌎 Deep within the constellation Cygnus, the black hole V404 Cygni occasionally unleashes powerful outbursts, ejecting matter at near light-speed in opposing jets. These rare events are so energetic that the black hole briefly outshines its entire host galaxy, offering a fleeting glimpse into the turbulent ballet around stellar remnants. ✨ #blackhole⚡#cygnus⚡#jets 👉subscribe Universe Mysteries

Universe Mysteries 🪐

@cosmomyst · Post #414 · 12.10.2025 г., 20:21

🪐 In the heart of the galaxy IC 310, astronomers have observed a quasar that suddenly switches between a quiet state and violent outbursts, blasting powerful jets of particles close to the speed of light. Quasars are some of the brightest objects in the universe, powered by supermassive black holes devouring matter, and IC 310’s unpredictable behavior shows how even these cosmic engines can rapidly transform, lighting up entire galaxies in moments. ✨ #quasars⚡#jets⚡#galaxies⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #370 · 03.10.2025 г., 22:21

🪐 The quasar PKS 0637-752, located about 7.8 billion light-years from Earth, shoots out a jet of particles more than 2 million light-years long—much farther than the diameter of our Milky Way. Quasars are the brilliant, active centers of young galaxies powered by material falling into supermassive black holes, and these enormous jets show how energy can be launched across intergalactic space by the universe’s most powerful engines. ✨ #quasars⚡#jets⚡#galaxies⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #677 · 13.02.2026 г., 12:21

🪐 At the edge of the galaxy M87, astronomers have tracked knots of matter racing outward in narrow jets from its supermassive black hole at more than 99% the speed of light. These plasma jets are powered by the black hole’s intense gravity and spin, yet how exactly the black hole manages to launch such focused, high-speed streams remains one of astrophysics’ biggest black hole mysteries. ✨ #blackholes⚡#jets⚡#plasma⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​

Universe Mysteries 🪐

@cosmomyst · Post #187 · 25.08.2025 г., 13:11

🪐 In the center of the galaxy NGC 2392, also known as the "Eskimo Nebula," astronomers have detected fast, energetic jets of gas blasting outwards at speeds of over 200 kilometers per second. These jets, launched by the dying central star, punch through surrounding shells of glowing gas, creating intricate, layered patterns that make this nebula one of the most visually stunning and mysterious cosmic objects observed by the Hubble Space Telescope. ✨ #nebula⚡#jets⚡#emission⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries ​

Universe Mysteries 🪐

@cosmomyst · Post #188 · 25.08.2025 г., 16:11

🪐 In the galaxy PKS 2014-55, astronomers have discovered a cosmic oddity known as an "X-shaped radio galaxy." This galaxy's energetic jets of particles, powered by a supermassive black hole, create two pairs of huge lobes that form a striking X pattern, suggesting a sudden flip in the black hole's rotation or direction—one of the rarest shapes found among radio galaxies. ✨ #phenomenon⚡#radiogalaxy⚡#jets⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries ​

Universe Mysteries 🪐

@cosmomyst · Post #392 · 08.10.2025 г., 15:21

🪐 In the spiral galaxy NGC 4945, located about 13 million light-years away in the constellation Centaurus, astronomers have measured jets of material shooting out from the galaxy's core at speeds approaching the speed of light—nearly 299,792 kilometers per second. This dazzling velocity, known as "relativistic speed," shows how cosmic engines powered by supermassive black holes can accelerate particles close to nature’s ultimate speed limit, producing jets that blaze across tens of thousands of light-years. ✨ #speedoflight⚡#relativistic⚡#jets⚡#NGC4945⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space 👉subscribe Universe Mysteries 👉more Channels ​