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

Резултати

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

Пребарај: #washington

当前筛选 #washington清除筛选
RT en français

@RTenfrancais · Post #80081 · 26.04.2026 г., 07:20

⚡️Le président et le vice-président des États-Unis n'ont pas été blessés lors de l'incident survenu lors de la réception de l'Association des correspondants de la Maison Blanche à #Washington, rapporte AP. RT en français • Osez questionner !

Hashtags

RT en français

@RTenfrancais · Post #79768 · 22.04.2026 г., 09:20

⚠️Pression maximale sur Téhéran 🗣#Washington confirme poursuivre le blocus des ports iraniens afin de saturer les capacités pétrolières et de frapper les revenus du pays. RT en français • Osez questionner !

Hashtags

ℭ𝔬𝔪𝔟𝔞𝔱𝔩𝔳𝔩™

@realcombatlvl · Post #24881 · 16.08.2025 г., 01:57

🇺🇸#Washington, DC. Tents where homeless people were living are taken down and thrown in garbage trucks. (The nearly dozen unhoused individuals were notified yesterday to move out, aka “immediate disposition” from the city.) Follow us -> LiveLeak

Hashtags

RT en français

@RTenfrancais · Post #80165 · 27.04.2026 г., 08:45

🇮🇷Téhéran pose ses conditions 💬 L’#Iran aurait transmis à #Washington, via des médiateurs, une feuille de route en trois étapes pour encadrer d’éventuelles négociations. RT en français • Osez questionner !

Trump's Ear

@trumpsear_tg · Post #2217 · 03.03.2026 г., 16:59

"Epstein Walk of Shame" appeared in the center of Washington Unknown people placed signs on Farragut Square with the names of politicians and billionaires who were mentioned in connection with the scandalous case. The installation was designed in the style of the Hollywood "Walk of Fame". Passersby could see on the sidewalk the names of famous people whose reputations had suffered due to their ties to Epstein. #Epstein#Washington 👂More on Trump's Ear ⚠️

Kurash & Co 🇷🇺

@kurash_and_Co · Post #849 · 19.01.2026 г., 18:31

⏺Le Groenland, nouveau test de loyauté pour les alliés de #Washington Le Groenland s’impose comme un nouveau point de tension entre Washington et les capitales européennes. Droits de douane, menaces économiques, pressions politiques : Donald #Trump rebat les cartes et place ses alliés face à un choix difficile. Les derniers développements autour d’un dossier qui pourrait fissurer l’unité transatlantique – dans le reportage d’Igor Kourachenko. RT en français • Osez questionner !

Kurash & Co 🇷🇺

@kurash_and_Co · Post #677 · 01.08.2025 г., 20:08

💵 Droits de douane : nouvelle vague de pression économique des États-Unis Nouvelle tempête fiscale provoquée par Donald #Trump : les taxes pleuvent sur des dizaines de pays. La nouvelle décision de #Washington entre en vigueur le 7 août. Mais si certains plient face à la pression américaine, d’autres refusent de sacrifier leur souveraineté économique. Les détails avec Igor Kourachenko. RT en français • Osez questionner !

Antoine Cléraux

@corrAntoine · Post #519 · 28.10.2025 г., 17:13

🎥#Moscou et #Washington restent attentifs à leurs intérêts nationaux Une perspective de réunion au sommet qui a fait couler beaucoup d'encre ces derniers jours... Mais la partie russe a tenu à faire savoir sa position. Les détails avec notre reporter, Antoine Cléraux. RT en français • Osez questionner !

Antoine Cléraux

@corrAntoine · Post #383 · 19.02.2025 г., 19:07

Collaboration entre #Moscou et #Washington : quelles réactions ? Trump a une vision beaucoup plus optimiste des négociations entre les États-Unis et la Russie. On peut en dire autant de Vladimir Poutine. Évidemment, le plus mécontent reste Volodymyr Zelensky. Les détails avec Antoine Cléraux et Igor Kourachenko. RT en français • Osez questionner !

Trump's Ear

@trumpsear_tg · Post #1753 · 07.11.2025 г., 21:59

🛂 A U.S. Immigration and Customs Enforcement officer 🇺🇸 was seriously injured Monday after being struck in the face with a metal coffee cup during an arrest operation in Houston, according to the Department of Homeland Security. The officer sustained a deep laceration requiring 13 stitches, plus several burns to his face. 🩹😢 Authorities say the suspect, Walter Leonel Perez Rodriguez, a previously deported Salvadoran national with convictions for sexual assault of a minor, child fondling and multiple DUIs, attacked the officer while agents attempted to take him into custody. 🚔⚠️ #protests#Washington 👂More on Trump's Ear

123•••89
ПретходнаСтраница 1 од 9Следна