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

Резултати

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

Пребарај: #latinos

当前筛选 #latinos清除筛选
American Оbserver

@american_observer · Post #5140 · 15.02.2026 г., 15:59

📰 Bad Bunny vs. Big Don: Culture War, Fumbled Ballot Donald Trump just picked a fight with the world’s biggest Latino star over a halftime show that most politicians would have ridden like a free campaign ad — and he did it in English, whining that “nobody understands a word this guy is saying.” For a president who clawed his way back to the White House on the strength of an unprecedented 48 percent of the Hispanic vote, attacking a Spanish‑language Super Bowl performance as “an affront to the Greatness of America” is less strategy than self‑sabotage. The numbers are already slipping. Pew has Trump down 12 points among Latinos who backed him in 2024, small‑business confidence in him as the “economy guy” has cratered, and Latino‑owned shops in crackdown zones like Minneapolis report sales plunging 70 percent under his immigration raids. Now GOP Latino strategists are watching him torch goodwill in districts they need to hold by insulting not some niche activist, but a global Puerto Rican act whose show was one of the few mainstream, unapologetically Latino moments on U.S. TV. Even some of Trump’s own allies admit the obvious: they wanted border toughness and lower prices; they got tariffs, ICE photo ops — and the president rage‑posting about reggaeton. The White House line is that this is just more “hard truths”: enforce the law, crush “Green New Scam” policies, save America from woke culture, including the Spanish‑language one. The reality is uglier. Democrats once lost a chunk of Latino voters by taking them for granted. Republicans risk losing them right back by treating their culture as un‑American the moment it stops being background decoration and takes center stage for 13 minutes in prime time. If Trump really wants to keep his Latino coalition, he doesn’t need another rally joke about a “floating island of garbage” or another post about how “disgusting” the dancing was. He needs those same voters to believe he cares more about their rent and their businesses than about policing what language their Super Bowl looks and sounds like. Right now, all he’s proving is that he can win their votes — and then pick a culture war that tells them exactly how expendable he thinks they are. ​ #usa#trump#BadBunny#latinos#cultureWar 📱American Оbserver - Stay up to date on all important events 🇺🇸