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

Резултати

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

Пребарај: #kenyan

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

@addisstandardeng · Post #21462 · 20.02.2026 г., 08:42

#Russia denies of recruiting #Kenyan citizens for war in #Ukraine The Embassy of the Russian Federation in Kenya has rejected allegations that it was involved in recruiting Kenyan citizens to fight in the conflict in Ukraine, describing the claims as part of a “dangerous and misleading propaganda campaign.” In a press release issued on February 19, the embassy said it had observed with “great concern” reports circulating in Kenyan media and public discourse regarding Kenyan nationals who allegedly traveled to Russia, joined the Armed Forces of the Russian Federation, and participated in combat operations in Ukraine. The statement comes after an intelligence official briefing presented to Kenya’s Parliament reported that 89 Kenyans were confirmed on the front line, 39 were hospitalized, and 28 were missing in action. https://addisstandard.com/?p=55260

Addis Standard

@addisstandardeng · Post #21908 · 01.04.2026 г., 16:28

Shipping disruptions strand 8 million kg of #Kenyan tea in #Mombasa as #US-#Israel war with #Iran hits exports Disruptions to global shipping routes linked to the ongoing war between the United States, Israel, and Iran have left nearly eight million kilograms of tea stranded in warehouses in Mombasa, threatening export earnings and farmer incomes, according to the East Africa Tea Traders Association. George Omuga, managing director of the association that runs the Mombasa tea auction, told Reuters that losses have been accumulating at roughly $8 million per week since 01 March. “The current conflict in the Middle East has had a direct impact, a negative impact on this auction,” Omuga said, noting that no tea shipments were currently leaving for Middle Eastern markets, which account for 20–25% of Kenya’s tea exports. https://x.com/addisstandard/status/2039378986518626404?s=20

Addis Standard

@addisstandardeng · Post #21163 · 23.01.2026 г., 09:22

News: #IMF-backed forex reforms cost #Ethiopia $2.6 billion in central bank losses Ethiopia’s central bank, the National Bank of Ethiopia (#NBE), has recorded losses equivalent to $2.6 billion following the country’s shift from a fixed to a market-based foreign exchange regime in July 2024, according to audited financial statements cited by the #Kenyan outlet The EastAfrican. NBE said it incurred 407.1 billion birr in foreign exchange losses during the financial year ending June 30, 2025, largely due to the revaluation of its foreign currency assets and liabilities after the exchange rate realignment. Foreign exchange losses rose sharply to 445.23 billion birr, from 38.13 billion birr the previous year. The surge pushed the National Bank of Ethiopia’s overall operating loss to 428.56 billion birr, up from 10.51 billion birr a year earlier, and drove the Bank into a negative equity position of 380 billion birr, raising concerns over its ability to continue... Read more: https://addisstandard.com/?p=54706

Addis Standard

@addisstandardeng · Post #21956 · 07.04.2026 г., 05:28

#UN envoy meets RSF leader in #Nairobi to discuss de-escalation in #Sudan The United Nations Personal Envoy for Sudan, Pekka Haavisto, met with Rapid Support Forces (#RSF) commander Mohamed Hamdan “Hemetti” Dagalo in Nairobi on Monday to discuss practical avenues for de-escalation. The meeting in the #Kenyan capital is part of Haavisto’s inaugural regional tour. It follows recent discussions in Khartoum with the President of the Transitional Sovereign Council, General Abdel Fattah al-Burhan, as the UN seeks to mediate an end to the nearly three-year-old conflict. UN spokesperson Stéphane Dujarric described the talks as a “constructive opportunity” to exchange views on protecting civilians. He noted that all stakeholders engaged by Haavisto have expressed readiness to cooperate with the world body. “This is encouraging and must swiftly translate into concrete progress towards ending..... https://www.facebook.com/AddisstandardEng/posts/pfbid0KVXwXxdPxbctPJpW5qK7Kwkw63bPeXrmU7q7Bjab37CvbqfZT7SuvSHFZqa4GrN2l