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

Пребарај: #eastprussian

当前筛选 #eastprussian清除筛选
Russian MFA 🇷🇺

@MFARUSSIA · Post #27998 · 13.01.2026 г., 18:01

#Victory81 🌟 On January 13, 1945, the #EastPrussian Offensive by the Red Army — one of the largest and most important #WWII operations against Nazi Germany — commenced. As a result of the operation in the #EastPrussia, the Soviet forces ultimatelydestroyed the Nazis' most capable, experienced, trained and equipped divisions on the entire Eastern front. The 'invincible reich' lost a critical strategic bridgehead in the Baltic region. The fortress city of #Königsberg — the cradle of German militarism and the starting point of eastward expansion — fell once and for all. The triumph of the Red Army in East Prussia held profound symbolic significance: the Nazis were decisively and completely crushed right there, where from, back in June 1941, they treacherously attacked our Motherland. ▪️“There it is, cursed Germany,”— that was what the Soviet soldiers-liberators said while stepping on the enemy's soil to pursue the condign retribution upon the Germans on their own territory. Those were exactly the accurate words to call the country where the most terrible evil the Mankind ever saw in its history — the Nazi scourge — was nurtured. The Germans sought Moscow’s fall, but instead they witnessed with disgrace the collapse of their own “great Reich.” *** The East-Prussian operation. The details January-April, 1945 The battles on the East Prussian theatre of operations lasted for 103 days, which made it the area that saw the longest continuous military engagement in the final year of #WW2. In the region, the Nazis constructed an exceptionally formidable defensive system, tailored to the specific features of terrain. The capital of East Prussia — the fortress city of Königsberg — was equipped with both external and internal urban fortification systems. In East Prussia, the Red Army faced the Nazi army with the personnel strength of some 780'000 Wehrmacht soldiers and officers. ⚔️ On January 13, 1945, the units of the 2nd Byelorussian and forces of the 3rd Byelorussian Fronts of the Red Army launched the offensive in East Prussia. Through the swift and overwhelming assault, the Soviet armor and the infantry, with the support of the aviaton, reached the Baltic Sea near Elbing (now the city of Elbląg in northern Poland) already on the third day of the operation, thus, having cut off any possible retreat routes for the enemy from East Prussia westwards. In less than two weeks, the Soviet forces broke through to Königsberg — the infamous Nazi citadel, which had allowed the Germans to dominate the eastern Baltics throughout the entire war, wasencircled. By February 10, 1945, the Nazi army group 'North' had been split into three isolated and tied down formations that were further driven to the coastline with no hope of escape. In April, the Königsberg garrison — numbering around 200'000 Wehrmacht soldiers and officers — was defeatedand surrendered. On April 9, the Red Army seized the fortress completely — the impregnable stronghold of the Third Reich, fortified with the latest military technology of WWII-era, finally fell. The loss of significant forces and militarily and economically vital region of East Prussia hastened Germany’s defeat. The Soviet forces inflictedhuge losses on the Wehrmacht and completely severed Third Reich’s maritime supply lines, crippling logistics for the blockaded 'Courland Pocket'. To commemorate the Heroic Victory in East Prussia, the medal 'For the Capture of Königsberg' was instituted in the USSR. The Medal was awarded to approximately 760'000 Red Army soldiers and officers. Aftermath WWII, under the terms approved by the Allied Leaders at the #PotsdamConference, much of East Prussia was incorporated into Poland, while a third of East Prussia territory, including the city of Königsberg (the Kaliningrad Region), became part of the Soviet Union. 🎖 By the Executive Order of President of Russia Vladimir Putin (signed on November 17, 2025), a new memorial date was established in our country — April 9, the Day of the Heroic Assault and Capture of Königsberg (1945).