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

Резултати

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

Пребарај: #html

当前筛选 #html清除筛选
GitHub Trends

@githubtrending · Post #15291 · 11.11.2025 г., 15:00

#html The Agent Development Kit (ADK) is an open-source toolkit that helps you build, test, and deploy advanced AI agents easily. It lets you create flexible, multi-agent systems using Python or Java, supports many AI models, and works with different deployment options. ADK offers a rich set of tools, built-in monitoring, and simple integration with Google services, making it easier to develop, debug, and scale your AI applications. This means you can focus on creating smart, efficient agents without worrying about complex setup or compatibility issues. https://github.com/google/adk-docs

Hashtags

GitHub Trends

@githubtrending · Post #15128 · 08.09.2025 г., 11:30

#html You get access to a huge, well-organized collection of 2,053 ready-to-use n8n automation workflows covering 365 different services, all searchable instantly with a super fast, mobile-friendly documentation system. This system offers lightning-fast full-text search, smart categorization by service and use case, and clear, meaningful workflow names, making it easy to find exactly what you need. You can run the documentation locally with simple setup steps, explore workflows by category or complexity, and even download or visualize them. This saves you time and effort in building automations, helps you discover proven workflows quickly, and supports efficient workflow management and customization. https://github.com/Zie619/n8n-workflows

Hashtags

GitHub Trends

@githubtrending · Post #15031 · 05.08.2025 г., 18:30

#html The International Obfuscated C Code Contest (IOCCC) is a programming contest where participants write the most confusing and hard-to-understand C code, often under 512 bytes. It started in 1984 to highlight bad coding styles and show how poor structure can ruin a program. The contest uses satire to teach programmers about C’s tricky parts and the importance of clear coding by showing what not to do. Winning entries are both educational and entertaining, helping you learn subtle C language details while having fun. The contest encourages you to explore and understand complex code, improving your programming skills and appreciation for good style. https://github.com/ioccc-src/winner

Hashtags

GitHub Trends

@githubtrending · Post #14884 · 29.06.2025 г., 13:00

#html You can easily create a secure Octra blockchain wallet by running a simple webserver on your computer. Just clone the wallet generator from GitHub, start the server, and open your browser to generate a new wallet. The tool shows your mnemonic phrase, private and public keys, and address, lets you test signatures, derive addresses for different networks, and automatically saves your wallet file. This helps you safely manage your Octra blockchain assets with full control over your keys and easy access to wallet features without needing complex setups. It’s a user-friendly way to secure and use your Octra wallet locally. https://github.com/octra-labs/wallet-gen

Hashtags

GitHub Trends

@githubtrending · Post #14779 · 03.06.2025 г., 11:30

#html "开往 Travellings" is a project that helps unknown websites get more visitors. It does this by creating a network where users can click a button to randomly visit other participating sites. This project started in 2020 and aims to make the internet more diverse and open. By joining, users can discover new sites and help smaller websites grow. It benefits users by introducing them to new content and supporting lesser-known creators. https://github.com/travellings-link/travellings

Hashtags

Plltxe.

@plltxe · Post #5358 · 04.04.2023 г., 04:46

Is Skia the works-everywhere feature-rich text rendering engine I’ve always been looking for? It seems to work on all sorts of platforms, even on #HTML Canvas with WebAssembly (!) It even used to have particles support, but was sadly removed from 2 months ago. https://skia.org/ 🐘

Hashtags

The Devs

@thedevs · Post #2095 · 29.12.2023 г., 11:02

HTML First, principles to make building web software easier, faster and more inclusive. #article#html @thedevs https://thedevs.link/9MhJrm

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