Можно ли в 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
🍿 'Dune: Part Three' promises the wildest chapter yet: Villeneuve hits the gas and Pattinson arrives like a desert demon
📆Release: December 18, 2026
🎭Genre: #ScienceFiction · #Thriller
I’m completely sold on Denis Villeneuve’s vision: if the first film was contemplative and the second was a war movie, 'Dune: Part Three' wants to be a full-on thriller, tighter, more physical, and far more brutal. ⚔️🌵 The story jumps ahead 17 years and puts Paul Atreides face-to-face with the consequences of his power, with Chani once again at the emotional center of it all.
What grabbed me most about the first trailer is its almost feverish energy: Timothée Chalamet radiates a deeply unsettling darkness, Zendaya looks set to have far more weight than Chani had in the book, and Robert Pattinson shows up as Scytale with a truly disturbing presence, somewhere between an albino messiah and an impossible villain. 😵💫 On top of that, Hans Zimmer once again turns Arrakis into the kind of IMAX experience that leaves you completely drained.
🍿 'Companion': Jack Quaid faces off against his robot girlfriend in a relentless thriller 🤖💥
📆Release: January 31, 2025
🎭Genre: #Thriller · #ScienceFiction
In 'Companion', Josh (Jack Quaid - 'The Boys') discovers that his girlfriend Iris (Sophie Thatcher - 'Yellowjackets') is a perfect android. When he modifies her settings, their relationship turns deadly, triggering a series of intense events in a remote cabin. Expect the typical shocking plot twists and a narrative reminiscent of Barbarian.
The chemistry between Quaid and Thatcher heightens the suspense, while director Drew Hancock delivers a fresh take on A.I., focusing on empowerment and self-discovery. 🎬✨
🍿 Exploring Cyber Horrors: 'Latency', the New Face of A.I. Terror 🎮
📆Premiere: June 14, 2024
🎭Genre: #ScienceFiction · #Horror
James Croke, a novel Australian director, immerses us in an anguishing science fiction thriller with 'Latency'. 🧠👾 Sasha Luss ('Anna') and Alexis Ren ('The Enforcer') shine in this story about an agoraphobic gamer who tests an A.I. device capable of reading her mind. What starts as an improvement in her game soon becomes a dark journey between reality and the subconscious. 🕹💔 Is this technological advancement a help or does it hide a more sinister force? Get ready for a chilling journey where the line between technology and horror is as thin as it is alarming!
🍿 'Terminator Zero': The rebirth of a legend in anime form
📆Release: August 29, 2024
🎭Genre: #Animation · #ScienceFiction
After several missteps in cinema, the 'Terminator' franchise reinvents itself with an exclusive anime on Netflix. 'Terminator Zero' takes us to Japan, where a scientist named Malcolm Lee becomes Skynet's target. The big twist is that the story shifts away from the franchise's classic American focus to explore how the war against the machines impacts other parts of the world. The series is a collaboration with Production IG, the studio behind hits like 'Haikyuu!!'. Could this be the resurgence fans have been waiting for? 👾
🍿 Robert Pattinson Multiplies Himself in 'Mickey 17', Bong Joon Ho's New Madness
📆Release: January 31, 2025
🎭Genre: #ScienceFiction · #DarkComedy
🎟 Bong Joon Ho, the genius behind 'Parasite', returns with 'Mickey 17'. Robert Pattinson multiplies himself, literally!, in this adventure where his character, an 'expendable' (disposable), dies and is cloned over and over again on a mission to colonize an icy planet. 🧊
The most curious thing is the peculiar tone of voice Pattinson has adopted, which already has fans obsessed. Plus, the cast is top-notch: Steven Yeun from 'Minari', Toni Collette from 'Hereditary', and Mark Ruffalo from 'The Avengers'. If 'Parasite' left us speechless, I can't wait to see what Bong brings us this time. 🚀
🍿 Discover the Deadly Silence of New York in 'A Quiet Place: Day One' 🌆🔇
📆Premiere: June 28, 2024
🎭Genre: #Suspense · #Horror · #ScienceFiction
Get ready for the release of 'A Quiet Place: Day One', where Lupita Nyong'o ('12 Years a Slave') and Joseph Quinn ('Stranger Things') immerse us in a New York transformed into a sound extermination camp. The tension escalates in a world where the slightest sound can be your doom. 🎬👾 In this thriller, we will see how desperate characters learn to manipulate chaos to survive, while facing ruthless creatures in a deafening silence. Michael Sarnoski's direction promises to expand this saga with an intense dramatic twist, exploring intertwined destinies at a critical moment for humanity. Don't miss this chilling journey to the day the world fell silent.
> 𝘴𝘦𝘳𝘪𝘦𝘴 · 🚀𝘣𝘰𝘰𝘴𝘵
🍿 'Dune: The Prophecy': The Prequel that Will Change the Dune Universe 🌌
📆Premiere: This fall
🎭Genre: #ScienceFiction · #Action · #Adventure · #Fantasy
🎬 Get ready to travel 10,000 years before Paul Atreides with 'Dune: Prophecy'! The Max series, based on the novel 'Sisterhood of Dune', follows the Harkonnen sisters, played by Emily Watson and Shirley Henderson, in their struggle to create the mythical Bene Gesserit sect. This powerful female order promises to redefine the fate of the galaxy. 🔮
What's interesting here is how we will see the beginnings of this intriguing sisterhood, previously explored in the movies by Denis Villeneuve. With a stellar cast and an engaging plot, 'Dune: The Prophecy' is a must-see journey for fans of the saga like me. 🚀✨
🍿 ‘Avengers: Doomsday’ brings Steve Rogers back… and now he’s a dad 👶🛡
📆Release: December 18, 2026
🎭Genre: #Superheroes · #Action · #ScienceFiction
✈️Add movie
Marvel has dropped the first official teaser and confirms what many of us already suspected: Chris Evans returns as Steve Rogers. No dialogue, the classic Avengers theme, and a very deliberate image: Steve rides his motorcycle to a farmhouse, cradles a newborn baby, and then pulls the Captain America suit out of storage, like someone flipping through an old album from a past life. It all ends with the on-screen line: ‘Steve Rogers will return in Avengers: Doomsday’. Pure nostalgia straight to the veins 🧨
I’m intrigued by the hook, but I’m also worried they might tamper with the perfect ending of Avengers: Endgame. To me, the teaser feels heavier on marketing than on cinema… 😅
🍿 ‘Avengers: Doomsday’ brings Steve Rogers back… and now he’s a dad 👶🛡
📆Release: December 18, 2026
🎭Genre: #Superheroes · #Action · #ScienceFiction
✈️Add movie
Marvel has dropped the first official teaser and confirms what many of us already suspected: Chris Evans returns as Steve Rogers. No dialogue, the classic Avengers theme, and a very deliberate image: Steve rides his motorcycle to a farmhouse, cradles a newborn baby, and then pulls the Captain America suit out of storage, like someone flipping through an old album from a past life. It all ends with the on-screen line: ‘Steve Rogers will return in Avengers: Doomsday’. Pure nostalgia straight to the veins 🧨
I’m intrigued by the hook, but I’m also worried they might tamper with the perfect ending of Avengers: Endgame. To me, the teaser feels heavier on marketing than on cinema… 😅
Isaac Asimov died on April 6, 1992. He created the Three Laws of Robotics. These laws state that a robot cannot harm a human, must obey humans, and must protect itself unless this conflicts with the first two laws.
🤖📚
[Read more 1]
[Read more 2]
@googlefactss
#IsaacAsimov#Robotics#ScienceFiction#DidYouKnow
📖Title : The Tangled Lands
✍️Author : Paolo Bacigalupi, Tobias S. Buckell
⭐️Rating : 3.63/5 (Goodreads)
📆Published : Feb 27, 2018
————————————————
Summary:The Tangled Lands by Paolo Bacigalupi and Tobias S. Buckell is a dark fantasy set in the decaying empire of Khaim, where every use of magic causes deadly bramble to grow, choking the land and threatening human survival. The empire, ruled by the oppressive Jolly Mayor, hoards magic for the elite while commoners suffer. The book comprises four interlinked novellas, each exploring resistance, environmental ruin, and personal sacrifice. Through the eyes of different characters—an alchemist, a thief, a child, and a warrior—we see a world caught between corruption and hope, where the cost of magic is far greater than its power.
————————————————
#fantasy#fiction#sciencefiction#magic#adult@Bookslibraryofficial@free_novellas@the_ancient_library