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

Пребарај: #gumart

当前筛选 #gumart清除筛选
Gumart Announcement 🛒

@gumartec · Post #277 · 07.07.2025 г., 08:27

🌐 Gumart Goes Global: GuGoGlobal Official Recap 🎬 From the streets of Paris to the shores of Cape Town, GuGoGlobal wasn’t just a campaign — it was a movement. 🕯 📌 Campaign Impact: 🌐 5 continents, 20+ cities 👥 100,000+ Gumart residents participated 🎁 $25,000+ in rewards distributed 🚀 Hundreds of check-in videos from real users 🙏 Thank you to every Gumart Resident, partner, and friend around the world who made this campaign unforgettable. Your energy, creativity, and belief in our vision are what bring Web3 to life — city by city, step by step.💸☄️ #GuGoGlobal#Gumart

Gumart Announcement 🛒

@gumartec · Post #280 · 21.07.2025 г., 08:15

🗺Where will you swipe next? 💳GuPay is still live — where will you swipe next? New York, Seoul, Manila, Miami… — We’ve already seen GuCard go global. 🌎 But for us, every payment counts — whether it's coffee near home or a flight across borders 📌 Let's share some moments with us: 1️⃣Use GuCard this week. 2️⃣Snap a photo and post to your X . 3️⃣Use hashtag #Gumart#GuPay Let’s show the world what crypto can actually do.🛒

Gumart Announcement 🛒

@gumartec · Post #181 · 05.01.2025 г., 15:19

✨🥳 GUCARD CREATIVE CONTEST IS HERE! 🥳✨ Are you ready to show off your creativity and love for Gumart? 💸 Join the Gucard Creative Contest and turn your ideas into amazing content! 🎥🖌 👍 How to Join: 1️⃣ Create unique content (video, photo, meme, or text) featuring Gucard or Gumart. 2️⃣ Post it on X or YouTube with the hashtag #Gucard#Gumart 🏆Prizes Await You: 🎖Main Prizes: 1st Place: 1,000 USDT (1 winner) 2nd Place: $500 USDT (3 winners) 3rd Place: $50 USDT (5 winners) 🌟 Community Choice Awards: 50 winners: $10 each (based on community engagement). 💳 Special Bonus: All winners will receive a free Gucard! 🗓Timeline: 🕐 Start: January 5, 2025 ⏳ End: January 19, 2025 🔥 Criteria for Winning: Creativity, quality, and interaction - bring your A-game! #GuMinigame

Gumart Announcement 🛒

@gumartec · Post #276 · 02.07.2025 г., 11:03

‼10,000+ TRANSACTIONS IN 20 DAYS 🤑 GuPay Team Cup – FIFA Club World Cup 2025 is going global - and it’s powered by BNB Chain ⚡️ From Real Madrid to Man City, 32 legendary football clubs are battling it out. But this time, it's not just on the field — it's on-chain. 🏟 📣 Gumart is rewriting what mass adoption looks like: 10,000+ real-world transactions made through GuPay across hotels, stores, and events — all in less than 3 weeks.⬆️ 🚀 Built on BNB Chain's trusted infrastructure, Gumart is leading the charge in making crypto usable, visible, and impactful in everyday life. ➖Want to join? Pick your team and make transactions with GuPay. Help your squad rise to the top. 🌐 Be where culture, payments, and crypto collide. #GuPayTeamCup#Gumart#BNBChain

Gumart Announcement 🛒

@gumartec · Post #244 · 15.04.2025 г., 07:23

🎬 Gumart is in Paris Blockchain Week 2025 🇫🇷 #GuGoGlobal campaign – a journey to take Gumart around the world and bring Web3 adoption closer to real life! 📍 First Stop: Paris Blockchain Week 2025 Our team just landed in Paris, the heart of innovation and fashion, to showcase Gumart at one of the most prestigious Web3 events in the world! From networking with top-tier founders and VCs to sharing the stage with the best builders in the space, Gumart is here to make waves. 🎥👉 Watch the highlight video from our Paris mission – and feel the energy! 💡We’re on a mission to show the world how Gumart is building the future of crypto payments, e-commerce, and DeFi — one region at a time. Real people. Real places. Real utility. 🚀 Next stop? Maybe your city. Don’t blink 👀 Let’s take Web3 mainstream – together 🌐 #GuGoGlobal#Gumart#PBW2025#Web3Adoption#ParisBlockchainWeek#CryptoInRealLife