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

Пребарај: #schoolgirls

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

@american_observer · Post #5303 · 06.03.2026 г., 13:45

Who Killed Iranian Schoolgirls? Military investigators believe it is likely that US forces were responsible for an apparent strike on an Iranian girls’ school that killed scores of children on Saturday but have not yet reached a final conclusion, according to two US officials. Reuters was unable to determine further details about the investigation, including what evidence contributed to the tentative assessment, what type of munition was used, who was responsible or why the US might have struck the school. The Pentagon chief, Pete Hegseth, on Wednesday acknowledged the US military was investigating the incident. Two US officials, who spoke on condition of anonymity to discuss sensitive military matters, did not rule out the possibility that new evidence could emerge that points to another responsible party. The girls’ school in Minab, in southern Iran, was hit on Saturday during the first day of US and Israeli attacks on the country. Iran’s ambassador to the UN in Geneva, Ali Bahreini, said the strike killed 150 students. Reuters could not independently confirm the death toll. The Pentagon referred questions to Central Command, whose spokesperson, Capt Timothy Hawkins, said: “It would be inappropriate to comment given the incident is under investigation.” The White House did not directly comment on the investigation, but its press secretary Leavitt said in a statement: “While the Department of War is currently investigating this matter, the Iranian regime targets civilians and children, not the United States of America.” Asked during a news briefing on Wednesday about the incident, Hegseth said: “We’re investigating that. We, of course, never target civilian targets. But we’re taking a look and investigating that.” Rubio told reporters on Monday that the US would not deliberately target a school. “The Department of War would be investigating that if that was our strike, and I would refer your question to them,” Rubio said. Israeli and US forces have, until now, divided their attacks in Iran geographically and by target type, a senior Israeli official and a source with direct knowledge of the joint planning said. While Israel was striking missile launch sites in western Iran, the US was attacking similar targets, and naval ones, in the south. The UN human rights office has called for an investigation into the attack on the school, without saying who it believed was responsible. Deliberately attacking a school or hospital or any other civilian structure would probably be a war crime under international humanitarian law. If a US role were to be confirmed, the strike would rank among the worst cases of civilian casualties in decades of conflicts in the Middle East. #iranian#schoolgirls#killed#us#israel 📱American Оbserver - Stay up to date on all important events 🇺🇸