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

Резултати

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

Пребарај: #ireland

当前筛选 #ireland清除筛选
POPULAR FRONT

@popularxfront · Post #6122 · 01.05.2026 г., 18:26

🇮🇪#Ireland: A 66-year-old man has been arrested and charged after a car bomb exploded outside a police station in Dunmurry, west Belfast, last Saturday. The perpetrator allegedly hijacked a delivery driver’s car and forced him to drive it to the location, where a gas cylinder had been placed inside and later detonated remotely. While some sources report he has been charged with attempted murder, others say he is also facing terrorism-related offences. Police believe the attack may be linked to the dissident republican group known as the New IRA. (via The Guardian, BBC & birminghammail)

Hashtags

POPULAR FRONT

@popularxfront · Post #6034 · 25.04.2026 г., 23:42

🇮🇪#Ireland: A suspected car bomb has exploded outside a police station in Dunmurry, Northern Ireland. Regional reports, including those from the Belfast Telegraph, state that the vehicle had been hijacked before being driven next to the police station, where it subsequently exploded. Police have cordoned off streets in the Kingsway area and are treating the situation as a “security incident.” No further details have been released at this time. (via Belfast Telegraph & @spicebag32; 📹 via @NiResponsevids on X)

Hashtags

POPULAR FRONT

@popularxfront · Post #5867 · 11.04.2026 г., 19:02

🇮🇪#Ireland: A man armed with a hammer breached security at Shannon Airport and climbed onto an American C-130 aircraft earlier today. Once on top of the plane, he attempted to damage it with the hammer. The man, who is in his 40s, was quickly arrested. No motive has been released, and his identity has not been disclosed.

Hashtags

POPULAR FRONT

@popularxfront · Post #5864 · 11.04.2026 г., 15:07

🇮🇪#Ireland: Up to 100 Gardaí were deployed to the Whitegate refinery, where protests have entered their fourth day amid rising fuel prices linked to the US and Israeli war against Iran. Footage shows Irish police forcibly attempting to remove trucks and tractors blocking the roads, with violent scenes breaking out. Officers can be seen kicking and stomping on farmers. Meanwhile, other videos appear to show protesters as young as 14 being pepper-sprayed by Gardaí.

Hashtags

POPULAR FRONT

@popularxfront · Post #5837 · 09.04.2026 г., 12:30

🇮🇪#Ireland: The Irish Army is set to be deployed across the country to remove heavy & agricultural vehicles blocking fuel depots, as protests over fuel prices enter their third day. Slow-moving convoys are targeting these sites over increasing fuel prices caused by the US and Israeli war against Iran. Police are now treating these actions as “blockades", with Gardaí (Irish police) reportedly requesting the assistance of the Irish army. In a statement, the Irish Minister for Justice said that once the army is deployed, people should not complain about any damage caused during the removal. (via CNN & limerickleader)

Hashtags

POPULAR FRONT

@popularxfront · Post #4697 · 24.01.2026 г., 11:11

🇮🇪#Ireland: ONH members fired a volley of shots in the Currynerin area of Derry last week. A 31-year-old man was arrested in connection with the event (though later released on bail) and a vehicle was seized. The PSNI have promised to increase ‘reassurance patrols as well as house-to-house enquiries and vehicle checkpoints in response. Repost via @spicebag32

Hashtags

POPULAR FRONT

@popularxfront · Post #4036 · 02.12.2025 г., 09:58

🇮🇪#Ireland: A new Irish militant group calling itself the "New Republican Movement" has announced its formation. In a video, where all members are armed, a masked man lists several motivations for creating the group, mostly focusing on mass immigration. They threaten Irish politicians with "immediate action", claiming to have their addresses. (via @real_eire on X)

Hashtags

Voyage.Travel.Tourism

@VOYAGE · Post #1298 · 10.02.2025 г., 13:14

📍Ireland’s architectural heritage – a journey back to the 19th century🇮🇪 📏 📏 📏 📏 📏 📏 📏 📏 🌟With its stunning castles, ancient ruins, and charming Victorian buildings, Ireland offers a glimpse into the past, where history and beauty come together in every stone. 📏 📏 📏 📏 📏 📏 📏 📏 #Ireland🇮🇪@voyage

Hashtags

Voyage.Travel.Tourism

@VOYAGE · Post #1200 · 19.12.2024 г., 13:14

📍Ireland’s architectural heritage – a journey back to the 19th century🇮🇪 📏 📏 📏 📏 📏 📏 📏 📏 🌟With its stunning castles, ancient ruins, and charming Victorian buildings, Ireland offers a glimpse into the past, where history and beauty come together in every stone. 📏 📏 📏 📏 📏 📏 📏 📏 #Ireland🇮🇪 @voyage

Hashtags

Voyage.Travel.Tourism

@VOYAGE · Post #761 · 17.02.2024 г., 13:04

Ireland, Rock of Cashel 🇮🇪 The Rock of Cashel is one of the most visited landmarks in Ireland, also known as St. Patrick's Rock. It is also referred to as the Rock of Kings. ⛰ 🏰 Located in the ancient Celtic cathedral in County Tipperary, Ireland. The castle, built in the 4th century, was the royal residence of the provinces of southern Ireland; after 100 years, St. Patrick settled there. After Cromwell's army attacked, the castle complex became a symbol of the resilience and courage of the Irish people. The castle grounds still preserve residential buildings, structures for agricultural purposes, and the ruins of the cathedral. #Ireland @voyage

Hashtags

ПретходнаСтраница 1 од 4Следна