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

Резултати

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

Пребарај: #independence

当前筛选 #independence清除筛选

@RusEmbMalta Press release On the anniversary of the Declaration of Ukraine’s independence 🔷 On August 24, 2024, Kiev celebrated a state holiday – the #Independence Day of Ukraine. The Kiev regime keeps trying to boast about its supposed “victories”, successful banderization and forced ukrainianization. It is the geopolitical and mercantile interests of the West that in fact stand behind its “support” of Ukraine, while this country is assigned the role of a “puppet” and “cannon fodder”. 🔷 The representatives of Zelensky's junta hardly dare to publicly discuss the violation of the provisions adopted in July 1990. 🔷 The heirs of Goebbels do not mention the real losses of the country and the missed opportunities during 33 years of “independence”, total depopulation and loss of whole industries. Kiev got into complete dependence on financial and material submits of the West, for which future generations of Ukrainians will have to pay. Read in full here

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40230 · 01.12.2025 г., 07:02

Since 1380, Iceland was ruled by Denmark. On December 1, 1918, Iceland became its own country with the same king as Denmark. In 1940, Iceland started making its own big decisions. On June 17, 1944, Iceland became a republic and stopped having a king. 👑🇮🇸 [Source] @googlefactss#Iceland#History#Independence#FunFacts

🌍 Qadrli yurtdoshlar! 🇺🇿 O‘zbekiston Respublikasi Vazirlar Mahkamasi huzuridagi Biznes va tadbirkorlik oliy maktabi jamoasi barchangizni 18-noyabr – “O‘zbekiston Respublikasining Davlat bayrog‘i qabul qilingan kun” bilan muborakbod etadi! 🇺🇿 Mustaqilligimiz hamda tinchligimiz ramzi bayrog‘imiz, g‘urur va faxrimiz timsoli yuksaklarda abadiy hilpirab tursin! #GraduateSchool#Uzbekistan#Flag#Independence 🔝Web-site |🔝Facebook | 🔝Instagram | 🔝Youtube

🇺🇿Biznes va tadbirkorlik oliy maktabi barcha yurtdoshlarimizni mustaqilligimizning 34 yilligi bilan muborakbod etadi. 🇺🇿Mustaqillik - yurtni, millatni birlashtiradigan yagona kuch, ko‘p millatli halqimizning irodasi, uning hurriyat haqidagi azaliy orzularidir. 🦅 Vatanimiz osmoni musaffo, sarhadlari daxlsiz, chegaralarimiz mustahkam, hayotimiz yana-da farovon, mustaqilligimiz va ravnaqimiz abadiy bo‘lsin! #GraduateSchool#Independence#34years#Development 🔝Web-site |🔝Facebook |🔝Instagram | 🔝Youtube

🇺🇿Biznes va tadbirkorlik oliy maktabi barcha yurtdoshlarimizni mustaqilligimizning 33 yilligi bilan muborakbod etadi. 🇺🇿Mustaqillik - yurtni, millatni birlashtiradigan yagona kuch, ko‘p millatli halqimizning irodasi, uning hurriyat haqidagi azaliy orzularidir. 🇺🇿 Vatanimiz osmoni musaffo, sarhadlari daxlsiz, chegaralarimiz mustahkam, hayotimiz yana-da farovon, mustaqilligimiz va ravnaqimiz abadiy bo‘lsin! 🦅Barchamizga yana bir bor O‘zbekistonimiz Mustaqilligining 33 yilligi muborak bo‘lsin! #GraduateSchool#Independence#33years#Development 🔝Web-site |🔝Facebook |🔝Instagram | 🔝Youtube

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40302 · 11.12.2025 г., 23:01

🇰🇪 Jamhuri Day (Swahili: “Republic Day”) — is Kenya’s national day, celebrated on December 12. It marks independence from Britain (12 Dec 1963) and becoming a republic (12 Dec 1964). Common observances: flag‑raising, presidential speeches, parades, cultural performances, and civic ceremonies. If you’re Kenyan or were there during the festivities, share your photos. @googlefactss#JamhuriDay#Kenya#Independence Siku njema ya Jamhuri kwa Wakenya wote.

8 сентябр Президенти Ҷумҳурии Тоҷикистон, Пешвои миллат муҳтарам Эмомалӣ Раҳмон дар паёми шодбошии худ ба муносибати 33-солагии истиқлоли давлатии Тоҷикистон тамоми мардуми сарбаланди кишвар ва ҳамватанони бурунмарзиамонро самимона табрик гуфта, ба ҳамаи онҳо хонаи обод, саодати рӯзгор, сулҳу оромӣ, ки асоси хушбахтии халқамон ва ободиву сарсабзии Ватани маҳбубамон мебошад, инчунин, комёбиву барори кор орзу намуданд. 8 сентября Президент Республики Таджикистан, Лидер нации уважаемый Эмомали Рахмона в своем поздравительном послании по случаю 33-й годовщины независимости, поздравив народ Таджикистана и зарубежных соотечественников, пожелал всем им семейного благополучия, счастливой жизни, мира и спокойствия, которые являются основой благоустройства нашей любимой Родины, безмятежной жизни народа, а также новых достижений и успехов. #ЭмомалиРахмон#EmomaliRahmon#Tajikistan#Президент#Таджики#Tajiks#Тоҷикон#Независимость#Independence President.tj | Facebook | Instagram | Telegram | X | Youtube

Congratulations on the 34th anniversary of independence: Putin tops the list, but Mirziyoyev stresses multi-vector policy. Different priorities for domestic and foreign audiences: Central Asia in the president’s speech and Russia–China in the official greetings. https://yep.uz/en/2025/09/uzbekistan-34th-independence-day-congratulations/ #uzbekistan#mirziyoyev#independence#putin#xijinping#trump#centralasia#politics#multivector

Venture Village Wall 🦄

@venturevillagewall · Post #3597 · 20.12.2024 г., 15:00

VCs Retreat from Crypto Market In 2023, analysts noted a significant decline in venture capital investments in cryptocurrency projects, returning to levels reminiscent of 2017. However, some initiatives are aiming to revive the industry’s original spirit of independence from VC influence, at least in principle. Insights provided by Oleg CasCoin for ForkLog. Read more #VC#Crypto#Investment#Market#Decline #2017 #ForkLog#OlegCasCoin#Independence#Initiatives#Analysis#Freedom#Trends#Industry#Finance#Blockchain#News#Updates#Economy#Future

Crypto M - Crypto News

@CryptoM · Post #65110 · 11.04.2026 г., 02:24

🚀 AI TRENDS | OpenAI's Sam Altman Addresses AI Development Concerns and Recent Incident OpenAI founder Sam Altman has expressed understanding of societal fears regarding the rapid development of artificial intelligence. According to Odaily, Altman acknowledged that the current period is marked by significant technological change, with associated risks escalating to systemic challenges at the societal level. He emphasized that AI power should not be concentrated in a few institutions and advocated for broader distribution through technological democratization and institutional constraints. Addressing a recent incident where his residence was targeted with a Molotov cocktail, Altman admitted to underestimating the impact of public narratives and emotions amid AI-related anxieties. He also acknowledged mistakes in company governance and conflict management, offering apologies for past actions. Furthermore, Altman reiterated his decision to reject Elon Musk's attempts to control OpenAI, ensuring the company's independent development. Previously, it was reported that the OpenAI founder's residence was attacked with a Molotov cocktail. #AI#OpenAI#SamAltman#AIdevelopment#technologicalchange#AIsociety#democratization#institutionalconstraints#Molotovcocktail#publicnarratives#conflictmanagement#ElonMusk#companygovernance#independence