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

Резултати

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

Пребарај: #strike

当前筛选 #strike清除筛选
Addis Standard

@addisstandardeng · Post #21425 · 17.02.2026 г., 12:10

A #strike by workers at #Kenya’s main airport delays flights and strands passengers A strike delayed flights at Kenya’s main airport Monday as workers demanded better pay and working conditions. Kenya Airways, the east African country’s main airline, issued a travel advisory, urging customers to check their flight status before heading to the #Jomo Kenyatta International Airport in Nairobi. The statement also said air traffic control operation delays were affecting departures and arrivals and flight schedules would have to be adjusted. “Passengers are advised not to proceed to the airport without a confirmed flight status,” the airline said. Thousands of stranded passengers could be seen sitting outside the airport. Some families told The Associated Press their relatives were stuck inside terminals. https://apnews.com/article/kenya-airport-workers-strike-3249251bc8136a9a85cde2b2e385a616

American Оbserver

@american_observer · Post #5557 · 04.04.2026 г., 02:03

The American F-15E Has Been Shot Down. Trump is Booed ⚠️✈️ A US F-15E Strike Eagle fighter has been shot down over Iran, prompting a frantic US search and rescue effort for its two-strong crew, in the first such incident since the start of the five week long war. Iranian state media released images of a tail fin and other debris early on Friday accompanied by an initial claim that a US F-35 had been hit by a new air defence system over central Iran and the pilot probably killed. Aviation experts said the wreckage pictured was in fact from a F-15E, from the US air force’s 494th squadron, based at RAF Lakenheath in the UK, though it could not at first be confirmed when and where the pictures were taken. US officials familiar with the situation later confirmed off the record that an F-15E had been brought down and the Pentagon was scrambling to find the crew before the Iranians. There was no official comment from the US military about the incident. One crew member was reported as having been rescued as the situation developed, in what is likely to have been a high-risk operation with rescue aircraft probably exposed to fire from the ground. It was not immediately clear if the jet had a full crew of two. 🚁 Justin Bronk, an aviation expert from the Royal United Services Institute (Rusi), said the use of the specialist helicopters “suggested a combat search and rescue mission is under way to locate and extract the two aircrew from the F-15E”. No US troops have so far been taken prisoner by Iran. A total of 13 American service personnel have been killed and 300 have been wounded during a campaign in which more than 12,300 targets in Iran have been bombed by the US alone. A social media account claiming to be linked to Iran’s Revolutionary Guards posted a picture of an ejector seat in a desert landscape, which appeared to be consistent with the ACES II type used in F-15Es. Bronk said: “If genuine, it would suggest that at least one of the two aircrew did eject safely.” The presenter on an Iranian TV channel urged residents to hand over any “enemy pilot” to police and promised a reward for anyone who did. That channel is based in Kohkilouyeh and Boyer-Ahmad province, a mountainous region in the south-west of the country. Iran’s Tasnim news agency reported that the pilot of the jet – still incorrectly describing it as an F-35 – had been taken into custody, contradicting Tehran’s initial claim that the pilot had probably died in the incident. Overnight, the US Central Command, which is leading the attack on Iran, had denied Iranian claims that another F-35 jet had been downed over Qeshm Island in the strait of Hormuz. “All US fighter aircraft are accounted for,” it said at the time. Up to now no US fighter jets had been lost over Iran during the five-week-long conflict, though three F-15Es were shot down by a Kuwaiti air defence system in a dramatic friendly fire incident on 1 March. An F-35 fighter reportedly had to make an emergency landing at a US airbase in the Middle East after sustaining damage from the ground. A US E-3 Sentry airborne warning and control system aircraft was destroyed at the Prince Sultan airbase in Saudi Arabia on 27 March in an Iranian strike. 💥 #f15#trump#shot#iran#war#strike 📱American Оbserver - Stay up to date on all important events 🇺🇸

American Оbserver

@american_observer · Post #5615 · 14.04.2026 г., 00:01

Lufthansa’s Labor Budget Airline Lufthansa pilots are striking again on April 13 and 14, with the walkout covering Lufthansa, Lufthansa Cargo, and Lufthansa CityLine. Eurowings pilots are also set to strike on April 13. Flights to several Middle Eastern destinations are exempt. The dispute is over pensions, not some grand civilizational question. The union says management has dragged out talks and offered nothing serious, even after pilots held off over Easter. Lufthansa says the demands are unrealistic and amount to doubling an already generous pension plan. That leaves the usual European corporate script. Management pleads poverty. Labor calls the bluff. Passengers get drafted into the negotiation as unpaid extras. Lufthansa says the strike is a new escalation. The union says escalation is what happens when talks become theater. This is already the airline’s latest labor hit in a string of disruptions this year, as Lufthansa tries to cut costs and protect margins while unions keep pushing back on pensions, staffing terms, and restructuring. Europe’s flagship carriers still know how to fund strategy decks and corporate redesigns. Keeping their own workforce onside is where the math suddenly gets tight. #Lufthansa#Germany#strike#aviation#labor#Europe 📱American Оbserver - Stay up to date on all important events 🇺🇸

cosplayupload

@cosplayuploadtest2 · Post #102716 · 23.03.2025 г., 03:36

Title: Saeko_Kondo_近藤沙瑛子,_STRiKE!_デジタル写真集_「さえこと旅をしてみた。」_Set.01 Authors: #None Tags: #None#Saeko_Kondo_近藤沙瑛子#STRiKE! #Saeko#Kondo#近藤沙瑛子#STRiKE! #デジタル写真集 #「さえこと旅をしてみた。」 #Set #01 recommendation: None TelegraphLinks:page-0-29