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

Пребарај: #sleazebag

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

@american_observer · Post #4824 · 11.01.2026 г., 13:59

The Iranian Protesters Attacked Khamenei As a “Sleazebag” and a “Low-life” Demonstrators have continued to take to the streets of Iran, defying an escalating crackdown by authorities against the growing protest movement. An internet shutdown imposed by the authorities on Thursday has largely cut the protesters off from the rest of the world, but videos that trickled out of the country showed thousands of people demonstrating in Tehran overnight into Saturday morning. They chanted : “Death to Khamenei, death to a sleazebag, a low-life!” in reference to supreme leader Ayatollah Ali Khamenei, and: “Long live the shah.” Crowds of protesters marched through the streets of Mashhad as fires burned around them, a show of defiance in the home town of Khamenei, who has condemned the protesters as “vandals” and blamed the US for fanning the flames of dissent. Iran’s internet shutdown is chillingly precise and may last some time. Trump has repeatedly threatened to intervene if Iranian authorities kill protesters, earning angry rebukes from Tehran. He said on Friday that the Iranian authorities were “in big trouble”, adding: “You better not start shooting, because we’ll start shooting too.” On Saturday night he said the US is “ready to help” as protesters in Iran faced an intensifying crackdown by authorities of the Islamic republic. “Iran is looking at FREEDOM, perhaps like never before. The USA stands ready to help!!!” Trump said in a social post on Truth Social, without elaborating. Those authorities warned people to not take part in protests on Saturday. The country’s attorney general, Mohammad Mahvadi Azad, said anyone who did so would be considered an “enemy of god”, a charge which carries the death penalty. State TV later clarified that anyone who even assisted protesters could face the charge. Despite the crackdown, more protests were planned for the weekend. Reza Pahlavi, the exiled son of the former shah of Iran, called for protesters to take to the streets on Saturday and Sunday and seize control of their towns. Pahlavi, who has emerged as an increasingly popular figure in the current round of protests, asked people to hoist the pre-1979 “lion and sun” flag which was used during his father’s rule. “Our goal is no longer merely to come into the streets. The goal is to prepare to seize city centres and hold them,” he said, promising he would return to Iran soon. The continuing block on the internet and mobile lines means it is hard for international media to estimate the size of the demonstrations, the largest in Iran in recent years, which pose a serious challenge to the regime’s rule. The Iranian Nobel peace prize winner Shirin Ebadi warned on Friday that security forces could be preparing to commit a “massacre under the cover of a sweeping communications blackout”, and said she had already received reports of hundreds of people being treated for eye injuries at a single Tehran hospital. Protesters were brought to the streets on 28 December by a deteriorating economy, but quickly began chanting anti-government slogans and demanding political reform. Though Iran has experienced mass protests before, analysts have said the battering of the regime during the 12-day war with Israel and the loss of Iranian-backed forces across the region have made it more vulnerable. Iranian authorities have become increasingly confrontational in their rhetoric towards protesters, casting them as being infiltrated and backed by Israeli, or US saboteurs. The Iranian army vowed in a statement on Saturday to foil “the enemy’s plots”, warning that undermining the country’s security was a “red line”. #uranian#protesters#khamenei#sleazebag#blackout#internet 📱American Оbserver - Stay up to date on all important events 🇺🇸