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

Резултати

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

Пребарај: #trailer

当前筛选 #trailer清除筛选
Journey to Fluency

@fluencyinenglish · Post #6861 · 14.02.2019 г., 05:57

‍#trailer ❇️Days Gone 🔹 Plot A global pandemic occurred which decimated the globe, turning millions of humans into feral cannibalistic creatures, called Freakers. The remnants of humanity have abandoned towns to seek refuge in the wilderness creating safe zones. ❇️Aftermath Deacon St. John, a member of the Mongrels MC, is among the survivors of the epidemic. Deacon drifts through the wasteland of the Pacific Northwest, never staying in one place for too long. Deacon often takes work as a Bounty Hunter/Mercenary, offering his services in exchange for supplies. However, Deacon learns that there is a price on his head adding to his list of enemies. @fluencyinenglish @ieltsstrategies

Hashtags

Journey to Fluency

@fluencyinenglish · Post #6282 · 26.07.2018 г., 19:31

‍#trailer ❇️GLASS Trailer (2019) @fluencyinenglish Security guard David Dunn uses his supernatural abilities to track Kevin Wendell Crumb, a disturbed man who has 23 personalities. @fluencyinenglish In the trailer (via THR), Sarah Paulson (American Horror Story series) appears as a psychiatrist who describes herself as someone that specializes in “individuals who believe they are superheroes.” Present among her patients at a Philadelphia asylum are Bruce Willis’ David Dunn, Samuel L. Jackson’s Elijah Price, aka Mr. Glass, and James McAvoy’s Kevin Wendell Crumb, aka The Horde. @fluencyinenglish

Hashtags

Journey to Fluency

@fluencyinenglish · Post #6278 · 25.07.2018 г., 10:08

‍#trailer ❇️The passage @fluencyinenglish The plot: 🔹When a botched U.S. government experiment turns a group of death row inmates into highly infectious vampires, an orphan girl might be the only person able to stop the ensuing crisis. @fluencyinenglish

Hashtags

Journey to Fluency

@fluencyinenglish · Post #6251 · 14.07.2018 г., 13:41

‍#trailer ❇️How It Ends [HD] | Netflix The plot: In the midst of an apocalypse, a man struggles to reach his pregnant wife, who is thousands of miles away. @fluencyinenglish @ieltsstrategies

Hashtags

Viral Today

@viral_today · Post #3229 · 21.11.2024 г., 11:31

The live-action adaptation of the beloved How to Train Your Dragon franchise is set to hit theaters on June 13, 2025 @Viral_Today / #trailer

Hashtags

Viral Today

@viral_today · Post #3032 · 19.09.2024 г., 16:38

Black Mirror Season 7 teaser just dropped This globally popular Netflix series has drawn millions of viewers with its chilling, dystopian stories about the dark side of technology. Past episodes like ‘Bandersnatch’ became worldwide hits, and this new season promises more twists and turns. @Viral_Today / #trailer

Hashtags

Viral Today

@viral_today · Post #2975 · 04.09.2024 г., 14:30

🌐 Warner Bros. has released the first trailer for A Minecraft Movie, which hits theaters in April 2025 and stars Jack Black and Jason Momoa. @Viral_Today / #trailer

Hashtags

123•••1011
ПретходнаСтраница 1 од 11Следна