Можно ли в 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
Политика Белого Дома — Л. Томас Блок
ФРС, торговая политика в Азии и промежуточные выборы
— Конгресс уходит на перерыв в связи с Днем поминовения.
— Пауэлл отправится в Белый дом на заседание во вторник.
— Заседание FOMC приближается 14-15 июня, наиболее вероятным представляется повышение ставки на 50 б.п.
— Байден встречается с лидерами Японии, Индии и Австралии для изучения вопросов торгового партнерства.
— Повлияли ли выборы в Джорджии на роль Трампа в Республиканской партии?
#uspolicy
Полные версии всех исследований доступны по подписке
Политика Белого Дома — Л. Томас Блок
— (❗️) Протокол заседания FOMC будет опубликован в среду в 2:00 (21:00 МСК). Фокус на направлении политики ставок.
— Сенатские слушания по Майклу Барру, который станет последним кандидатом Байдена на пост главы ФРБ.
— Промежуточные выборы: Кандидаты, поддерживаемые Трампом, хорошо выступили на прошлой неделе в PA и NC, но некоторые волнения могут быть замечены на этой неделе в GA, где губернатор Кемп, похоже, одержит победу над кандидатом, поддерживаемым Трампом. Но поддерживаемый Трампом кандидат в Сенат Уокер, похоже, тоже идет к победе.
— Помощь Украине демонстрирует растущий раскол в рядах республиканцев.
#uspolicy
Полная версия данного исследования доступна здесь
🇺🇸U.S. AI Memos Reveal a Quiet Convergence with EU Risk Regulation
Two new AI policy memos issued by the White House—M-25-21 and M-25-22—may read like a manifesto for innovation, acceleration, and barrier removal. But beneath the rhetoric lies a nuanced regulatory shift that echoes the EU’s high-risk AI framework. Memo M-25-21, in particular, introduces risk management provisions for “high-impact” AI use cases—defined broadly and open-endedly across six categories, including civil rights, critical infrastructure, and access to essential services.
This flexible and expansive categorization quietly challenges the narrative that the U.S. is lagging in AI governance. In fact, for those familiar with the EU AI Act’s Annex III, the similarities are striking—and in some areas, the U.S. memo is even stricter. A reminder that real regulation doesn't always come with loud announcements.
#AI#AIGovernance#USPolicy
🇺🇸White House Releases National AI Legislative Framework
The White House published a national AI legislative framework aimed at centralizing regulation and preventing U.S. states from enacting their own AI laws. The initiative follows an executive order signed by President Donald Trump in December, which blocked state-level enforcement, and reflects a light-touch federal approach covering areas from data centers to AI-enabled scams.
The framework outlines six objectives for Congress, including tools for parental control over children’s digital presence, streamlined permitting for data centers, and measures to address AI-related fraud. It also proposes balancing intellectual property rights with the need to train AI systems on real-world data and calls for limits on government influence over content moderation by technology providers.
The administration emphasizes sector-specific regulation instead of a single rule-making authority and seeks to preempt state laws governing AI model development. According to White House officials, the framework is intended to support innovation while addressing safety risks associated with broader AI deployment.
#AIRegulation#USpolicy#AIgovernance#TechLaw#ArtificialIntelligence
🇺🇸California Moves to Tighten AI Standards in State Procurement
California Governor Gavin Newsom signed an executive order to strengthen requirements for AI companies seeking to work with the state. The order directs the development of stricter procurement standards, requiring vendors to demonstrate responsible AI policies and meet privacy and security benchmarks to prevent misuse of their technologies.
The initiative contrasts with recent federal actions rolling back AI-related protections. It also expands the state’s use of generative AI in public services, including tools designed to help residents navigate government programs and benefits based on life events such as employment or starting a business.
#AIRegulation#USpolicy#AIethics#PublicSectorAI#DataProtection
Over the past century, oil has played an outsized role in Venezuela. It is no wonder that the United States, in its neverending regime-change plots, chose to target this crucial sector with crushing sanctions.
Our latest video examines the crude reality of coercive measures against the Venezuelan oil industry.
#Venezuela#Sanctions#USPolicy#VenezuelanOil#OilIndustry
https://youtu.be/lwcB4Z9jwGA
🇺🇸U.S. Department of Labor Launches “Make America AI-Ready” Initiative
The U.S. Department of Labor announced the “Make America AI-Ready” initiative, a free AI literacy course designed to provide workers with foundational AI skills. The program delivers training via text messages, allowing users to complete the course in seven days with daily 10-minute sessions, aiming to ensure accessibility, including for individuals without reliable internet or devices.
Developed in partnership with education technology company Arist, the initiative aligns with the White House’s AI Action Plan and America’s Talent Strategy. The course covers five areas: understanding AI principles, exploring use cases, directing AI through prompts, evaluating outputs, and responsible use. According to officials, the program is intended to prepare workers for an AI-driven economy and expand access to AI-related skills and opportunities.
#AIRegulation#AILiteracy#FutureOfWork#USpolicy#AIgovernance