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

Резултати

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

Пребарај: #liberty

当前筛选 #liberty清除筛选

Liberty. Equality. Fraternity. And don't forget to leave the keys... Today, TON and Telegram represent a decentralized spaceship with 13 million inhabitants on board, ahead of its time. Cryptocurrency gives many people hope for a free and secure life. Web3 is not just about pixel images and taps; it is also a technology uniting millions of people who today collect coins together and tomorrow could make an important decision for the whole world. In the few years since TON was established, communities have sprung up around the world—in almost all CIS countries, as well as in Denmark, Italy, Nigeria, Iran, South Korea, Hong Kong... these are just the ones that come to mind because I personally read them. But the community itself is huge and, most importantly, international. It is also very friendly. Just look at the scale of support for Pavel Durov with the ✈️ symbol that hundreds of channels with multimillion audiences simultaneously posted. I have never encountered racial or religious animosity in TON chats. No one has offered me drugs or weapons. Politics are generally not discussed in crypto communities, except in terms of its impact on the exchange rate. Overall, this is a community of enthusiasts who are eager to learn new things and share their knowledge with others. So, I can confidently say that this is a healthy and sane community. Against the backdrop of current events, it is worth remembering that the idea around which more than 13 million people worldwide have united is alive and thriving. If all these people lived in one country, that country would rank 75th in population among all the countries in the world. The main idea of the Telegram messenger and TON cryptocurrency is Freedom. Yes, the very freedom that its ideological inspirer Pavel Durov is currently deprived of. #FreeDurov#TON#Telegram#Liberty

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40120 · 18.11.2025 г., 11:01

For over 20 years, the US has detained 39 Muslim men at Guantánamo Bay, with 27 never charged. The CIA operated secret "black sites" where at least 119 Muslim men were held and at least 39 tortured, without accountability. This system of unlawful detention, rendition, and abuse has cost billions, fueled propaganda by armed groups, and undermined global human rights. [Read more] @googlefactss#HumanRights#Guantanamo#Torture#Accountability#usa#liberty#LandOfTheFree

Venture Village Wall 🦄

@venturevillagewall · Post #3944 · 21.01.2025 г., 22:00

Trump Calls for Ross Ulbricht's Release Senator Rand Paul urges President Trump to free Ross Ulbricht, the founder of Silk Road. Meanwhile, Coinbase CEO Brian Armstrong states Trump is excited about a Strategic Bitcoin Reserve, aiming to be the first Bitcoin President. Additionally, Binance's CEO predicts a crypto all-time high in 2025 amid clearer U.S. regulation under Trump. Critical Metals Corp raises $500M for Bitcoin reserve strategy as they accept BTC as treasury asset—first Nasdaq company in critical minerals sector to do so. 🔗 Related articles from Watcher Guru and CoinDesk. #Bitcoin#USDC#Crypto#Trump#Coinbase#Binance#HesterPeirce#SEC#Decentralization#Finance#Investment#CriticalMetals#Aviation#Regulation#Liberty#Decentralized#Blockchain#CryptoNews#VC #Bitcoin#USDC#Crypto#Trump#Coinbase#Binance#HesterPeirce#SEC#Decentralization#Finance#Investment#CriticalMetals#Aviation#Regulation#Liberty#Decentralized#Blockchain#CryptoNews#VC

Kayleigh McEnany

@kayleighmcenany · Post #2252 · 09.01.2025 г., 08:23

Trump and the American Empire recovery/2 In the grand scheme, reclaiming America’s global dominance is critical to preserving liberty worldwide. Trump’s focus on expanding influence into Greenland, Canada, and the Panama Canal reflects this understanding. By securing these strategic positions, America strengthens its economy, protects vital trade routes, and curtails the growing influence of adversaries. The fight isn’t just about geography—it’s about values. Trump’s vision recognizes that American strength is a bulwark against tyranny. A strong America doesn’t just serve Americans—it serves the cause of freedom for all. But the ultimate success of this strategy depends on one thing: vigilance. America must remain true to its founding values of liberty, autonomy, and justice. That means balancing global influence with domestic safeguards, ensuring that while we project strength abroad, we don’t compromise freedom at home. Only then can the American empire thrive as a force for good, outshining authoritarian rivals like China and Russia, and ensuring a world where liberty reigns supreme. #Canada#Greenland#Denmark#Trump#MAGA#China#Russia#Iran#War#Israel#America#US#USA#Liberty#Freedom#Politics#Panama Part 1 @KayleighMcEnany