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

Пребарај: #arrested

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

@american_observer · Post #4989 · 29.01.2026 г., 12:59

Iran: More than 42,300 People Have Been Arrested, Killed and Tortured Doctors are being arrested in Iran for helping save the lives of some of the tens of thousands injured during Iran’s brutal crackdown on anti-regime protests, with at least one surgeon now at risk of being sentenced to death. The arrests and death sentence are part of a campaign of “revenge”, say human rights groups, after healthcare workers and doctors refused to ignore the plight of badly injured protesters shot or stabbed at close range. An Iranian surgeon, Alireza Golchini, 52, from the central city of Qazvin, has been charged with “moharebeh” (waging war against God), which can carry the death penalty, according to the Norway-based rights group Hengaw. The US state department yesterday called for his release. The US-based Human Rights Activists News Agency, whose figures have been reliable during previous crackdowns, says it has verified more than 6,000 dead and has more than 17,000 more recorded deaths under investigation. “He was arrested in a violent manner in front of his wife and son, who is only 11. They beat him up so badly during arrest, they broke his arm, ribs and dragged him out of his home. My family is terrified,” said Med dr. Golchini. A few days before his arrest Golchini, who also treated protesters during the 2022 Woman, life, freedom protests, had posted a note on his social media, says Nima, sharing his number and asking injured patients to contact him for treatment. “All he did was his duty of saving lives as a medical doctor. He had sworn to save people’s lives. How can any doctor not stand by his oath? I am worried not only for him, but also for other healthcare workers who have been arrested for simply standing by their sworn oath.” Iranian authorities have not publicly commented on Golchini’s detention, nor have they confirmed any charges against him. But Iran’s judiciary chief, Gholamhossein Mohseni Ejei, has urged authorities not to show any leniency towards protesters. “We should not remain silent in the face of those who seek to exploit the situation and disrupt the security and calm of the people,” he said. IHRNGO also reported the arrest of a volunteer first responder who had turned his home into an improvised medical shelter. According to the source, he was detained on 14 January after security forces raided his house, where he had provided care to more than 20 injured protesters, two of whom later died. “He was taken away in an extremely brutal manner and was severely beaten,” a source told IHRNGO, adding that security forces smashed the windows of the house, destroyed the interior and severely damaged his car during the raid. At least 42,324 arrests have been made across the country with limited information on their fate, according to the US-based Human Rights Activists in Iran, which says the regime is putting pressure on medical networks as a means of reducing support for the injured. A statement published yesterday by the US state department on X demanded the release of Golchini and “all the brave doctors who have helped their fellow countrymen”. It continued: “President Trump has clearly stated that no executions should take place in Iran and that there will be consequences if the government takes such actions.” #iran#tortures#killed#arrested#doctors 📱American Оbserver - Stay up to date on all important events 🇺🇸