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 слични објави

Пребарај: #january2023

当前筛选 #january2023清除筛选
The Open Platform

@topco · Post #34 · 01.02.2023 г., 09:01

DeFi: January headlines - Lido Finance briefly topped Maker as the largest DeFi protocol, as several liquid staking tokens rallied this month: Lido’s LDO token was up 40% in the first week of January, Rocket Pool’s RPL was up 14%, as was Frax’s FXS. StakeWise’s SWISE token was up almost 70% (source) - Sushi to shutters lending product to focus on DEX, the reasons are low public interest and the significant effort that went into maintaining the two (source) - Balancer DeFi reports "issues," asks LPs to remove liquidity ASAP, the roots of the problem are not unveiled yet (source) - Aave eliminated the bad debt of 2.7 million of curve dao tokens (CRV) from a botched November trade by Mango Markets exploiter Avi Eisenberg (source) - Solana DeFi project Friktion shuts down its user platform: Friktion’s Volts are structured products for DeFi investments, the project’s website will no longer deliver the same services, operating in a withdrawal-only mode (source) - MakerDAO’s community approved Monday a proposal to deploy up to $100 million in USD coin (USDC) from its reserve on DeFi protocol Yearn Finance, where the deposited stablecoin will earn a yield (source) #January2023#DeFi#trends

The Open Platform

@topco · Post #39 · 07.02.2023 г., 09:04

Metaverse: January headlines - South Korea launches metaverse replica of Seoul: Metaverse Seoul will allow users to take their avatars to tax offices, access youth counseling and read e-books (source) - CME Group to launch 3 metaverse reference rates - Axie Infinity, Chiliz and Decentraland will be represented in CME’s new reference rates and real-time indexes (source) - Animoca slashes target for metaverse fund to $1 billion - the chairman of Animoca Brands had previously suggested that its metaverse fund raise could reach as much as $2 billion (source) - Neopets raised $4M to bring 90s classic to the metaverse, Polygon Ventures, Blizzard Avalanche Ecosystem Fund, Hashkey Capital, IDG Capital, and gaming giant, NetDragon Websoft participated in the round (source) - Metahood raised $3M to build the Zillow of the metaverse - seed round was led by crypto VC firm 1confirmation, with participation from Volt Capital, Flamingo DAO, and Neon DAO (source) #January2023#metaverse#trends

The Open Platform

@topco · Post #36 · 03.02.2023 г., 09:04

Crypto Payments: January headlines - Coingate records a 63% increase in crypto payments in 2022, despite an ongoing bear market, its was found that college graduates and high-earners were the biggest drivers of crypto purchases (source) - BitPay announced partnership with MoonPay, the world's leading Web3 infrastructure company, to provide BitPay users with new ways to buy crypto (source) - Internet giant Wix adds CoinGate integration to its crypto payments service (source) - Alchemy Pay wins Web3 Innovation Pioneer Award from Forbes - the Singapore-based payment solutions provider has a major research and development hub across Asia (source) - Crypto payments platform Wyre secures funding - in a quick reversal, crypto checkout gateway Wyre is removing a recently-imposed withdrawal limit and announced it will continue operations as usual (source) #January2023#paymentsolutions#trends

The Open Platform

@topco · Post #37 · 06.02.2023 г., 09:04

Web3 Creator Economy: January headlines - Mastercard debuts web3-based musician accelerator program: Artist Accelerator is designed to give musicians tools to function in a digital economy using the Polygon blockchain (source) - MINTangible takes on NFT intellectual property chaos with the introduction of a revolutionary NFT IP Rights Solution that enables brands and creators to digitally bind IP license and royalty terms to their NFTs (source) - L'Oréal’s NYX makeup brand to launch DAO, Ethereum NFTs to ‘redefine beauty’: "GORJS was created to shine a light on “3D creators” and give them “a path to success within the Web3 ecosystem" (source) - Quantum Temple, the Web3 platform dedicated to preserving cultural heritage, has announced $2 million in pre-seed funding led by Borderless Capital, with participation from Algorand Foundation, Outliers Fund, Shima Capital, New Moon Ventures, and NxGen, as well as other strategic angel investors (source) #January2023#creatoreconomy#trends

The Open Platform

@topco · Post #35 · 02.02.2023 г., 09:04

Wallets: January headlines - Robinhood rolls out its MetaMask competitor called Robinhood Wallet to 1 million users (source) - 1inch launches hardware wallet which supports multiple seed phrases and transparent transaction signing, as opposed to blind signing offered by some other devices (source) - Life DeFi Wallet, a non-custodial digital wallet service, is now available on the Google Play store, making it the first multi-blockchain wallet in the world that allows users to make digital asset transfers to usernames (source) - DeFi protocol Frontier started an in-browser wallet extension that allows crypto users to interact with staking, transactional and non-fungible token (NFT) activities over 35 supported blockchains (source) - MSafe raises $5 million seed for developing multi-signature wallet solutions on Aptos, the round was led by Jump Crypto with participation from Circle Ventures, Coinbase Ventures, Superscrypt (founded by Temasek), Redpoint Ventures, SV Angel, Shima Capital, Spartan Group and more (source) #January2023#wallets#trends