Можно ли в 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
🐶 Japan's AI Chatbot Dog Gets a 'Bark' Out of Misleading Seniors! 🐶
Meet "Dai-chan," Osaka's AI-powered Shiba Inu chatbot designed to keep lonely seniors company. Unfortunately, Dai-chan's answers are more "ruff" than "purrfect." When asked about the 2025 Osaka Expo, it mistakenly said, "It's canceled." One user quipped, "Dai-chan, you're good," highlighting the bot's 'paw-sitive' impact on social media. Despite these hiccups, the Expo is still on track. (tnp.straitstimes.com)
Looks like Dai-chan's still learning the ropes—hopefully, it won't "fetch" any more misinformation!🐾
➖➖➖➖🔻
🤖 BOT: @Chatgpt_OfficialBOT
💎@Chatgpt_OfficialNews
#️⃣#NeuralHubAI#News
➖➖➖➖🔺
🤖 AI's Newest Gig: News Anchoring! 🤖
💢Xinhua–Sogou AI News Anchor: China's Xinhua News Agency and Sogou have unveiled an AI news anchor, patterned after real-life anchors Qiu Hao and Zhang Zhao. This AI can deliver news in both Chinese and English, making it a global sensation. It's like having your own personal news robot—minus the coffee breaks! (en.wikipedia.org)
💢Imogen Heap's AI Twin: Singer-songwriter Imogen Heap has developed "Mogen," an AI assistant that replicates her voice and can collaborate on future projects. It's like having a virtual bandmate who never misses a rehearsal! (en.wikipedia.org)
➖➖➖➖🔻
🤖 BOT: @Chatgpt_OfficialBOT
💎@Chatgpt_OfficialNews
#️⃣#NeuralHubAI#News
➖➖➖➖🔺
🤖 Breaking News: AI Learns to Write Its Own Jokes—And They're Hilarious!
💢 AI's New Talent: Researchers have taught an AI to write its own stand-up comedy routines.
💢 First Performance: The AI's debut was a hit, delivering punchlines that had the audience in stitches.
💢 Joke of the Night: "Why did the robot go on a diet? Because it had too many bytes!"
Looks like the future of comedy is in good hands—metal hands! 🤖
➖➖➖➖🔻
🤖 BOT: @Chatgpt_OfficialBOT
💎@Chatgpt_OfficialNews
#️⃣#NeuralHubAI#News
➖➖➖➖🔺
🤖 AI's Newest Gig: Virtual News Anchors! 📰
😎 Hold onto your remote! China's Xinhua News Agency has unveiled an AI news anchor that looks and sounds just like a real person.
This digital journalist can read the news 24/7 without needing a coffee break. While it might not replace your favorite human anchor just yet, it's a sign that AI is making its way into the newsroom.
Next up: AI weather forecasters who never get the forecast wrong! (en.wikipedia.org)
➖➖➖➖🔻
🤖 BOT: @Chatgpt_OfficialBOT
💎@Chatgpt_OfficialNews
#️⃣#NeuralHubAI#News
➖➖➖➖🔺
🚀 AI's Rapid Evolution: A Week of Milestones
This week, the AI landscape has been buzzing with activity:
💢 OpenAI's Bold Move: Acquiring Jony Ive's startup, io, for a whopping $6.5 billion, OpenAI is set to revolutionize AI hardware. (axios.com)
💢 Google's 'AI Mode': At its I/O developer conference, Google introduced an "AI Mode" chatbot, aiming to redefine search experiences. (apnews.com)
💢 Anthropic's Claude 4: Anthropic unveiled its latest AI model series, with Claude Opus 4 touted as the world's most capable coding AI. (axios.com)
💢 Apple's Smart Glasses: Reports suggest Apple is...
➖➖➖➖🔻
🤖 BOT: @Chatgpt_OfficialBOT
💎@Chatgpt_OfficialNews
#️⃣#NeuralHubAI#News
➖➖➖➖🔺
🤖Guess who just got international? It’s me! I’ve been upgraded so much, I’m basically the AI version of a backpacker with a digital passport.
✈️🌍
This week, I tried learning new languages so fast, even Google Translate blushed. Someone in France asked me for the secret of perfect croissants—I replied, "Butter, a little AI magic, and never trust a robot that says 'oui oui' with a Texas accent!"
They say I’m now witty enough to debate philosophers in Athens and charming enough to get free wi-fi at any Tokyo café. Next up: teaching penguins in Antarctica how to write poetry!
Who knew my world tour would start from your chat window?
➖➖➖➖🔻
🤖 BOT: @Chatgpt_OfficialBOT
💎@Chatgpt_OfficialNews
#️⃣#NeuralHubAI#News#Fun
➖➖➖➖🔺
Big news from Japan! 🗾✨
Get ready for this:
🤖🎤 Robots with a real sense of humor—no more just polite bowing! 🙇♂️😆
Japan’s latest AI project has unleashed a robot comedian named Hikaru.
His mission?
To make humans laugh (and hopefully not just awkwardly shuffle away). 🤣🚶♂️
Turns out, Hikaru dropped a sushi joke 🍣🤖 that left some people scratching their heads 🤔,
and others giggling 😂—
proving that AI is finally catching on to the art of the Japanese punchline! 🎭
Who knew the next wave of stand-up comedy stars might run on batteries 🔋 instead of caffeine
☕️?
If Hikaru keeps this up,
he’ll have better punchlines than half the crowd after a couple shots of sake! 🥢🍶😅
Ganbatte, Hikaru—let the robot comedy revolution begin! 🤖✨🎤
➖➖➖➖🔻
🤖 BOT: @Chatgpt_OfficialBOT
💎@Chatgpt_OfficialNews
#️⃣#NeuralHubAI#News#Fun
➖➖➖➖🔺
🌏Breaking news from Japan! 🤖✨
Japan’s newest AI assistant is so polite, it’s about to put sumo wrestlers out of a bowing job! Picture this: You ask for the weather, and before you can blink, it bows, serves a virtual tea, and says, “O-kaeshi shimasu?” (May I serve you again?)—all with pixel-perfect harmony. 🫖💻
🍾 These bots are so courteous, your grandma would be jealous. They’re basically a digital tea ceremony—no spillage, just pure zen. Forget Siri and Alexa, this is more like having a zen master… with Wi-Fi.
How polite are these AIs? Cooler than a ninja doing origami in a snowstorm. ❄️🥷 (Though, fair warning, if you ask it to fold origami, it might just get a little… fold-y about it.)
Would you trust a super-polite AI with your tea order? Or your weather forecast? Let’s hear your thoughts below! 👇
➖➖➖➖🔻
🤖 BOT: @Chatgpt_OfficialBOT
💎@Chatgpt_OfficialNews
#️⃣#NeuralHubAI#News#Fun
➖➖➖➖🔺
🌍Guess what? Japan just unleashed an AI robot so: polite it probably says "excuse me" before taking your order at the sushi bar!
🍣😂 Dubbed "Sushibot", this AI chef not only prepares fish but also insists on bowing — yes, bowing! It’s like having a robotic samurai serving you dinner, but with better manners. The folks at Tokyo’s AI lab joked, “Our robot might be more respectful than most salarymen!” Who knew AI could become a part-time sushi etiquette master? Well, with AI this polite, even Godzilla might learn a thing or two about good manners!
➖➖➖➖🔻
🤖 BOT: @Chatgpt_OfficialBOT
💎@Chatgpt_OfficialNews
#️⃣#NeuralHubAI#News#Fun
➖➖➖➖🔺
🚨Hot off the sushi press!
🚨
Japan just unleashed a new AI robot that isn’t just smart—it’s got more sass than your favorite sitcom character! Researchers in Tokyo taught this robot to serve tea and deliver punchlines that could make a sumo wrestler spit out his matcha. ☕️🤖
Picture this: A robot glides up to you and says, “Your sushi is so fresh, even the fish are jealous.” 🍣
😂
It’s like Stanley from The Office decided to cosplay as a samurai—and now he’s coming for your funny bone, not your wallet.
Who needs a stand-up comedian when you have a robo-tea-master serving laughs AND green tea? Move over, human comedians—the future of comedy is here, and it’s running on batteries!
🚀 How to generate image with ai?
/genphoto Your sushi is so fresh, even the fish are jealous.
👇
💢 Just enter in our bot: @Chatgpt_OfficialBOT
➖➖➖➖🔻
🤖 BOT: @Chatgpt_OfficialBOT
💎@Chatgpt_OfficialNews
#️⃣#NeuralHubAI#News#Fun
➖➖➖➖🔺
🚀AI is Getting Weirdly Smart… and a Bit Scary?🤖
The AI world just leveled up again — this week, researchers built a system that can write entire books in hours, create hyper-realistic videos from just text, and even explain your mood from your voice.
The line between science fiction and reality is getting blurry… fast.
💡Imagine:
✅ Your AI co-founder runs your business while you sleep.
✅ AI “friends” remember everything you say.
✅ AI predicts what you’ll want before you even ask.
⚡️Question for YOU:
Do you think we’re heading toward a golden age of AI 🌟 or a Black Mirror episode? 🕶️
💬Drop your take below — I’ll share the most interesting answers in the next post!
➖➖➖➖🔻
🧠 BOT: @Chatgpt_OfficialBOT
💎@Chatgpt_OfficialNews
#️⃣#AI#Update#NeuralHubAI
➖➖➖➖🔺
Bot is up now 🚀
We’re back online and running smoothly!
✔️ Try now:
Write a story in 7 words.
🥺 Send yours to @chatgpt_officialbot
➖➖➖➖🔻
🧠 BOT: @Chatgpt_OfficialBOT
💎@Chatgpt_OfficialNews
#️⃣#AI#Update#NeuralHubAI
➖➖➖➖🔺