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

Резултати

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

Пребарај: #america

当前筛选 #america清除筛选
RTDocumentary

@rtdocumentary · Post #697 · 03.05.2022 г., 13:59

#video#America In 1986, a two-year-old girl died in a fire in the United States. Her mother's former roommate was accused of arson and imprisoned on death row. But some of the evidence turned out to be fake, and the prosecution witnesses refused to testify. Finally, after 21 years, the court recognised the verdict was a mistake and released him. The film Imprisoned: The Man with a Cigarette is one of the episodes of the RT Documentary series about mistakes in American justice. Follow: https://t.me/rtdocumentary

Suriyakmaps

@suriyak_maps · Post #9681 · 11.03.2026 г., 15:36

The conflict between #Iran and #America is unconventional How Iran is conducting the war and the nature of its military operations. The impact of this conflict on the region and the world. video link (Dubbed):https://youtu.be/egZ_KHA2pW8?si=iUJw2x3lLoyGFbgO

Islamic World News

@iswnews_en · Post #17305 · 12.03.2026 г., 01:58

🇮🇷/🇺🇸🇦🇪🔥Iran's missile/drone attack on US army positions and interests in Dubai. Tonight, the UAE and the city of Dubai witnessed several retaliatory attacks by Iran. #Iran#America#UAE

RTDocumentary

@rtdocumentary · Post #780 · 17.05.2022 г., 13:59

‘I am a black gay immigrant woman ... to hold this position’. So the new White House Press Secretary decided to talk about just that at her first briefing. Karine Jean-Pierre is 44 years old, and she raises a daughter with her lesbian partner. She has an ideal profile for the US Democratic Party: Jean-Pierre is an African American with Haitian roots, a representative of the LGBT community who studied at the prestigious Columbia University. Karine Jean-Pierre replaced Jen Psaki as US President’s spokeswoman. Previously Karine stood behind the podium only when Psaki was ill or on vacation. Now, this is who we’ll learn about the administration’s policy direction and possible further sanctions against Russia. But do sanctions have a strong bite? Watch the film Sanctions: Opportunity in Disguise. #WhiteHouse#America Follow: https://t.me/rtdocumentary

Papa & Vaticano - News

@papaevaticanonews · Post #9571 · 06.03.2026 г., 15:17

Il 9 e 10 marzo, nella suggestiva cornice dei giardini papali di #CastelGandolfo, prenderà il via la Global Alliance, un’iniziativa internazionale dedicata all’ecologia integrale e alla sostenibilità globale, promossa dal Centro di Alta Formazione Laudato si’ e dall'Università di Notre Dame. All’evento inaugurale parteciperanno rappresentanti di oltre sessanta università di #Europa, #Asia, #America e #Africa, ed esponenti delle principali organizzazioni internazionali impegnate nella lotta alla crisi climatica. Due giorni di confronto, riflessione e scambio di esperienze per costruire un approccio integrato alla sostenibilità, basato sui principi dell’Enciclica Laudato si’ e della Dottrina Sociale della Chiesa. La Global Alliance nasce con l’obiettivo di connettere università, centri di ricerca, comunità e istituzioni impegnate nella promozione di pratiche sostenibili, valorizzando le sinergie tra ricerca, educazione e azione comunitaria. La rete intende creare un’infrastruttura condivisa capace di amplificare l’impatto globale dell’ecologia integrale, unendo fede, scienza e giustizia sociale, per contrastare così degrado ambientale, disuguaglianze e ingiustizie ecologiche. Tra i risultati attesi: la costituzione di una rete globale di istituzioni, la creazione di gruppi tematici per lo sviluppo di agende di ricerca e strumenti formativi, e il rafforzamento della visibilità e del contributo cattolico nel dibattito internazionale sulla sostenibilità. Il Cardinal Fabio Baggio, Direttore Generale del Centro di Alta Formazione Laudato si’ e tra gli ideatori della Global Alliance, sottolinea: "La Global Alliance nasce come un cammino condiviso di speranza: unire scienza, comunità e fede per custodire il creato, proteggere i più fragili e costruire insieme un futuro sostenibile, giusto e rispettoso di ogni persona". "Notre Dame è profondamente impegnata nella visione morale della Laudato Si’, per salvaguardare coloro che si trovano ai margini e prendersi cura della nostra casa comune - dichiara il Presidente dell’Università, Robert A. Dowd, C.S.C. -. Siamo onorati di collaborare con il Vaticano in questa Alleanza Globale, che riunirà illustri leader e ricercatori nel campo della sostenibilità e dell’ecologia integrale provenienti da tutto il mondo, per creare un futuro più giusto e resiliente per tutti". La Global Alliance rappresenta così una rete strategica di speranza, capace di tradurre l’impegno per l’ecologia integrale in progetti concreti e duraturi a livello globale.

Addis Standard

@addisstandardeng · Post #21690 · 12.03.2026 г., 11:04

#Op_ed: Aggression as Norm: How #America’s triad of hegemony destabilizes global order, redefines sovereignty In this op-ed, Hassen Mama Muse contends that the February 2026 strikes on #Iran and the arrest of Nicolás Maduro signal a new era where “the immediate security and economic imperatives of the American unipole override established global norms.” He views this as the culmination of a century long strategy of U.S. primacy exerted through diplomacy, military force, and covert influence. Beyond power projection, #Washington uses “weaponized interdependence”—leveraging economic and financial networks to shape peripheral states. To counter this, Hassen urges the Global South to pursue a “Multiplex World” focused on economic autonomy and “Decentred Globalism,” prioritizing regional hubs and horizontal partnerships instead of superpower dominance. https://addisstandard.com/?p=55782

Addis Standard

@addisstandardeng · Post #21292 · 03.02.2026 г., 11:02

#Commentary: From Internal Unity to Strategic Diplomacy: #Ethiopia’s playbook for dealing with Trump’s #America In this commentary, Teferi Tafa examines how the Trump administration’s renewed engagement over the Grand Ethiopian Renaissance Dam (#GERD) and Nile water disputes has intensified Ethiopia’s strategic challenges. He notes that “Ethiopia faces a critical moment that demands not just reactive diplomacy but a comprehensive strategy rooted in internal cohesion and enhanced bargaining power.” Highlighting internal division and conflicts as the greatest vulnerability, Teferi states, “No amount of diplomatic maneuvering can compensate for a house divided against itself.” He concludes, “Ethiopia’s response to this diplomatic moment will define not just its relationship with the Trump administration but also its trajectory for the coming decade.” https://addisstandard.com/?p=54948

Suriyakmaps

@suriyak_maps · Post #10145 · 24.03.2026 г., 00:05

The escalation continues… and #Iran denies any negotiations with #America. Missile strikes and underground bases remain operational despite the bombing. The #Yazd base becomes a military enigma, baffling everyone. And the #Lebanon front… video link (Subtitled):https://youtu.be/DOebjiVJxlU?si=24HNJ2m9osQy8a4L

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