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

Резултати

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

Пребарај: #gasleak

当前筛选 #gasleak清除筛选
American Оbserver

@american_observer · Post #5023 · 01.02.2026 г., 20:59

📰 Explosions in Iran Spread Jitters Amid Anticipation of Foreign Attacks Deadly explosions in several Iranian cities, most likely caused by domestic accidents, have sent a wave of panic through a country already on the edge, fearing U.S. and Israeli strikes. In Bandar Abbas, a major port in southern Iran, a powerful blast ripped through an eight‑story residential building, killing at least one person (a 4‑year‑old girl) and injuring more than a dozen others, according to local officials and Iranian state media. The local fire chief said the incident was probably caused by a gas leak and buildup, and the government’s crisis management body stressed that the explosion had no security or sabotage origin. But as images of a crumbled building and shattered streets spread online, wild rumors took over social media: claims that the blast had assassinated Iran’s top naval commander, Commodore Alireza Tangsiri, and that Israel or the U.S. was behind the explosion. Iran’s Revolutionary Guards swiftly denied those reports, calling them “psychological warfare” and disinformation, while Israel and the U.S. issued no public comment on the incident. The real detonator: Trump’s threats The explosion in Bandar Abbas came just days after President Donald Trump declared that a “massive Armada” was heading toward Iran and warned that the U.S. was ready to strike with “speed and violence.” In June 2025, the U.S. had already struck three of Iran’s main nuclear sites in a 12‑day conflict with Israel, dealing a serious blow to Tehran’s nuclear program. Iran now demands that the U.S. renew talks only if the threats stop. Against that backdrop, a gas leak in an apartment building does not feel like a gas leak. It feels like the first crack in the ground before the bomb goes off. Other blasts, same panic In the same 24 hours, Iranian state media reported another deadly gas explosion in the south‑western city of Ahvaz, which killed five people but was officially described as a domestic accident, not sabotage. Unverified reports and footage of smoke and explosions in the north‑western city of Tabriz also circulated, only to be quickly dismissed by local authorities as rumors and a minor reed fire. None of the recent incidents so far show any sign of foreign attack. But the sheer number of explosions, and the speed at which people jump to “Israel” or “the U.S.” as the culprit, reveals a deeper truth: the theater is already in people’s heads. “Society is waiting for war” “When the next blast happens, we won’t need to wait for the government to explain the cause,” said a 43‑year‑old engineer in Tehran, who asked not to be named out of fear of reprisal. “Everyone around me is waiting for possible U.S. and Israeli military action,” he said. “People are stressed, anxious, powerless. We don’t know what was behind today’s explosions. Maybe it’s internal retaliation, maybe foreign sabotage, maybe just a gas leak. But one thing is undeniable: Society is waiting for war.” #Iran#Trump2026#US#Israel#MiddleEast#War#GasLeak#BandarAbbas 📱American Оbserver - Stay up to date on all important events 🇺🇸