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

Резултати

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

Пребарај: #distro

当前筛选 #distro清除筛选
Linuxgram 🐧

@linuxgram · Post #18038 · 12.03.2026 г., 05:50

📰 AlmaLinux 9 and 10 Gain Official NVIDIA CUDA Support NVIDIA now officially supports AlmaLinux for CUDA workloads, with driver and userspace packages available in the distro's repositories. 🔗 Source: https://linuxiac.com/almalinux-9-and-10-gain-official-nvidia-cuda-support/ #distro

Hashtags

Linuxgram 🐧

@linuxgram · Post #18602 · 28.04.2026 г., 14:55

📰Most Linux regret is actually distro regret, and you probably gave up too soon Let's say I'm introducing ice cream to an alien. I get a cone, put a dollop of vanilla ice cream onto it, and hand it over. The alien gives the ice cream a lick, says it doesn't like the flavor, and then states that, as a result, ice cream just isn't for them. Of course, people wouldn't allow the alien to believe that all ice creams taste bad because it didn't like the vanilla flavor; instead, they'd recommend different flavors of ice creams and... 🔗 Source: https://www.xda-developers.com/linux-regret-actually-distro-regret/ #distro#linux

Linuxgram 🐧

@linuxgram · Post #18595 · 28.04.2026 г., 09:56

📰IPFire 2.29 Core Update 201 Linux Firewall Distro Released with DNS Firewall IPFire 2.29 Core Update 201 hardened Linux firewall distro is now available for download with DNS Firewall, Intrusion Prevention System improvements, updated components, and other changes. 🔗 Source: https://9to5linux.com/ipfire-2-29-core-update-201-linux-firewall-distro-released-with-dns-firewall #distro#linux

Linuxgram 🐧

@linuxgram · Post #18557 · 24.04.2026 г., 13:04

📰 Tails 7.7 Anonymous Distro Adds Detection of Outdated Secure Boot Certificates Tails 7.7 anonymous Linux distribution is now available for download with automatic detection of outdated Secure Boot certificates, Tor Browser 15.0.10, and other changes. 🔗 Source: https://9to5linux.com/tails-7-7-anonymous-distro-adds-detection-of-outdated-secure-boot-certificates #distro#linux

Linuxgram 🐧

@linuxgram · Post #18309 · 04.04.2026 г., 13:31

📰 This lightweight Linux distro is what old hardware has been waiting for Void Linux won’t be the right distro for everyone, but on old hardware, its lean design can feel like a second life. 🔗 Source: https://www.xda-developers.com/lightweight-linux-distro-what-old-hardware-waiting-for/ #distro#linux

Linuxgram 🐧

@linuxgram · Post #18160 · 23.03.2026 г., 18:55

📰 Every gaming Linux distro is about to share the same foundation, and it could change everything We finally have an answer to Linux gaming's fragmentation problem. 🔗 Source: https://www.xda-developers.com/every-gaming-linux-distro-share-the-same-foundation/ #distro#linux

Linuxgram 🐧

@linuxgram · Post #18085 · 17.03.2026 г., 09:54

📰 Ageless Linux Emerges to Protest OS-Level Age Verification Laws And thankfully, it's more than just a Linux distro without age verification. 🔗 Source: https://feed.itsfoss.com/link/24361/17300603/ageless-linux #linux#distro

Linuxgram 🐧

@linuxgram · Post #17982 · 05.03.2026 г., 15:18

📰MX Linux 25 may be the best distro for old PCs that nobody talks about If you have an old laptop you're not ready to throw away yet, MX Linux may just be the best way to give it a new life. 🔗 Source: https://www.xda-developers.com/mx-linux-25-may-be-best-distro-old-pcs-nobody-talks-about/ #linux#distro

Linuxgram 🐧

@linuxgram · Post #17917 · 27.02.2026 г., 13:44

📰 Bazzite triples its userbase in 8 months as gamers seek a Windows alternative People have begun to wake up to the idea that, in some situations, installing a gaming-oriented Linux distro will give you a better experience than Windows 11. Once pinned as the one operating system you don't want to use if you care about gaming, Linux has since come leaps and bounds with tech like Proton that allows games to run on the FOSS operating system without the game's developers lifting a finger. 🔗 Source: https://www.xda-developers.com/bazzite-triples-its-userbase-in-8-months-as-gamers-seek-a-windows-alternative/ #linux#distro

Linuxgram 🐧

@linuxgram · Post #17911 · 26.02.2026 г., 21:23

📰 Tails 7.5 Updates Tor Browser to 15.0.7 and Improves Thunderbird Security Tails 7.5, a privacy-focused Linux distro, upgrades Tor Browser to 15.0.7, updates the Tor client to 0.4.9.5, and improves Thunderbird security. 🔗 Source: https://linuxiac.com/tails-7-5-privacy-focused-linux-distro-released/ #linux#distro

Linuxgram 🐧

@linuxgram · Post #18561 · 24.04.2026 г., 17:47

📰 Canonical finally gives Launchpad (a bit of) a glow-up Launchpad, the home of Ubuntu development, has finally received some design attention. Canonical last updated the site’s homepage back in 2024, but many of the pages that the distro’s developers actually use or reference on a regular basis have remained untouched for the best part of a decade. Now that’s starting to change. 🔗 Source: https://www.omgubuntu.co.uk/2026/04/ubuntu-launchpad-website-revamp #distro#ubuntu

Linuxgram 🐧

@linuxgram · Post #18514 · 21.04.2026 г., 17:38

📰 Ubuntu confirms the 26.10 codename, and it sounds strange… Ubuntu has announced the codename for Ubuntu 26.10 is… “Stonking Stingray”. As codenames go it’s certainly unique. The distro gives each release a codename has an alliterative pairing of adjective and animal, the latter of which becomes the release mascot. The tradition dates back to the first Ubuntu release in 2004 (dubbed ‘Warty Warthog’). Ubuntu 26. 🔗 Source: https://www.omgubuntu.co.uk/2026/04/ubuntu-26-10-codename-confirmed #distro#ubuntu

ПретходнаСтраница 1 од 3Следна