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

Резултати

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

Пребарај: #neovim

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

@githubtrending · Post #15553 · 10.03.2026 г., 12:00

#lua#github#neovim Octo.nvim lets you edit and review GitHub issues, pull requests, and discussions right in Neovim. Just open with commands like `//github.com/user/repo/issues/1` or `w` to sync changes instantly. Add reactions, labels, assignees, or reviewers easily. This saves time by keeping all GitHub work in your editor—no browser switching—boosting productivity for developers managing repos. https://github.com/pwntester/octo.nvim

GitHub Trends

@githubtrending · Post #15599 · 03.04.2026 г., 11:30

#rust#filesearch#lua#neovim#neovim_plugin#rust FFF is a super-fast fuzzy file finder for AI agents and Neovim users. It excels at grepping, fuzzy matching, and globbing with built-in memory that ranks results by frecency, git status, file size, and more for typo-proof searches. Install easily via script for AI (like Claude) or Lua for Neovim (keys like ff for files, fg for grep). This saves you time and tokens by finding code instantly, skipping useless files, and boosting productivity on big repos. https://github.com/dmtrKovalenko/fff.nvim

GitHub Trends

@githubtrending · Post #14753 · 26.05.2025 г., 12:00

#tree_sitter_query#hacktoberfest#neovim#nvim_treesitter#tree_sitter Nvim-treesitter is a plugin for Neovim that makes it easy to use Tree-sitter, a modern parsing tool, for better syntax highlighting and code understanding in your editor[1][2]. It automatically installs and manages language parsers, so you don’t have to do it manually, and supports many programming languages out of the box. With nvim-treesitter, you get more accurate and faster syntax highlighting, smarter code navigation, and features like incremental selection, indentation, and code folding, all based on the actual structure of your code[4]. This means your code is easier to read and work with, and you can move around and edit code more efficiently. While some features are still experimental, using nvim-treesitter can greatly improve your coding experience in Neovim. https://github.com/nvim-treesitter/nvim-treesitter

GitHub Trends

@githubtrending · Post #14955 · 13.07.2025 г., 13:00

#shell#awesome#awesome_list#neovim#neovim_plugins#nvim_lua Neovim is a powerful, extensible text editor based on Vim, designed for usability and customization. It supports a vast collection of plugins tailored specifically for Neovim features, including plugin managers, language servers (LSP), AI coding assistants, syntax highlighting, fuzzy finders, file explorers, Git integration, debugging tools, and more. These plugins enhance coding productivity by adding features like code completion, project management, smooth navigation, and UI improvements. Using Neovim with these plugins lets you create a personalized, efficient coding environment that can boost your workflow, support many programming languages, and integrate modern tools like AI assistants and debuggers directly into your editor. https://github.com/rockerBOO/awesome-neovim

GitHub Trends

@githubtrending · Post #15096 · 26.08.2025 г., 11:30

#lua#layout#lua#neovim#neovim_plugin#neovim_ui#nvim#plugin#scratchpad#ui#ux#zen_mode#zenmode The no-neck-pain.nvim plugin for Neovim centers your active editing window by adding empty buffers on each side, creating padding that keeps your focus in the middle of the screen. It works right away without setup, supports multiple tabs, split windows, and integrates with popular file tree and dashboard plugins. You can customize its width, colors, and behavior, and even use the side buffers as scratchpads for notes. This helps reduce neck strain and improves focus, especially on wide monitors, by keeping your code or text centered and easy to read without distractions. https://github.com/shortcuts/no-neck-pain.nvim