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

Резултати

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

Пребарај: #peru

当前筛选 #peru清除筛选
POPULAR FRONT

@popularxfront · Post #6148 · 03.05.2026 г., 19:48

🇵🇪#Peru: Former Senate candidate Jorge Luis Alcalde Alfaro was assassinated by a hitman in broad daylight in Trujillo three days ago. He was about to enter his car when another vehicle pulled up and opened fire. He later died on the way to the hospital. (📹 via @cartelwatchnet on X & Caretas.pe)

Hashtags

Voyage.Travel.Tourism

@VOYAGE · Post #1537 · 21.08.2025 г., 12:14

🗺 Peru 🇵🇪 🟠It turns out you can ski not only on snow but also on sand. Such skiing takes place in the Ica Desert in Peru! This is called sandboarding. 📏 📏 📏 📏 📏 📏 📏 📏 #Peru | @voyage

Hashtags

Voyage.Travel.Tourism

@VOYAGE · Post #1442 · 05.06.2025 г., 12:14

🗺 Peru 🇵🇪 🟠It turns out you can ski not only on snow but also on sand. Such skiing takes place in the Ica Desert in Peru! This is called sandboarding 📏 📏 📏 📏 📏 📏 📏 📏 #Peru🇵🇪@voyage

Hashtags

Voyage.Travel.Tourism

@VOYAGE · Post #1282 · 02.02.2025 г., 13:14

🗺 Peru 🇵🇪 📏 📏 📏 📏 📏 📏 📏 📏 🟠It turns out you can ski not only on snow but also on sand. Such skiing takes place in the Ica Desert in Peru! 📏 📏 📏 📏 📏 📏 📏 📏 This is called sandboarding. 📏 📏 📏 📏 📏 📏 📏 📏 #Peru🇵🇪@voyage

Hashtags

Voyage.Travel.Tourism

@VOYAGE · Post #987 · 20.06.2024 г., 12:14

🗺 Peru 🇵🇪 It turns out you can ski not only on snow but also on sand. Such skiing takes place in the Ica Desert in Peru! This is called sandboarding. #Peru @voyage

Hashtags

Voyage.Travel.Tourism

@VOYAGE · Post #662 · 27.12.2023 г., 06:01

Peru🇵🇪 Impressive natural masterpiece - the Rainbow Mountains in the Cusco region. ⛰🌈 The colorful layers of these mountains were formed millions of years ago from red sandstone, which, under the influence of climatic conditions, underground water, and mineral impurities, became stained with yellow, green, white, and other colors. #Peru @voyage

Hashtags

Voyage.Travel.Tourism

@VOYAGE · Post #542 · 27.11.2023 г., 13:04

Peru🇵🇪 A walk with a magnificent view of Machu Picchu. Machu Picchu is a legendary city nestled in the heart of the Andes at an altitude of 2400 meters. It is an ancient Inca settlement located between two mountain peaks. 🏔 When tourists gaze at the ruins of the city of Machu Picchu, which stand out dramatically among the jungle-covered mountain peaks and steep slopes, and the terraces descending into the valley, their breath is taken away. #Peru @voyage

Hashtags

RTDocumentary

@rtdocumentary · Post #328 · 28.11.2021 г., 10:01

The right to die #video#Peru Ana Estrada is confined to bed most of the time and can breathe only with a respirator. She lives with polymyositis, a rare muscle disease with no cure. Since 2016, Ana has been writing a blog called ‘Ana seeks a dignified death’. In addition, she started a legal battle to decide to end her life ‘when the time comes’. Assisted death is illegal in her country of Peru. Peru is primarily a Catholic country, where euthanasia is prohibited alongside same-sex marriage and abortion. However, in 2021 a court ruled in favour of Ana and cleared anyone assisting in her death of criminal charges. Ana says she would decide to die when she could no longer write her blog. On this day in 2000, the Dutch lower house of parliament voted to legalise euthanasia. Thus, the Netherlands became the first country that allowed mercy killings. Euthanasia is also legal in Spain, Belgium, Luxembourg, Canada and Colombia. Follow: https://t.me/rtdocumentary

Hashtags

RTDocumentary

@rtdocumentary · Post #209 · 12.09.2021 г., 10:10

#video#Peru Hundreds of thousands of Peruvian women were forcibly sterilised between 1996-2000 as part of President Alberto Fujimori’s family planning programme. The initiative was launched to reduce poverty and cut birth rates among the poor. While it was supposed to be consensual, women involved in the programme say otherwise. Most of the victims came from poor indigenous communities. Josefa was at home when nurses came and forced her to go to the hospital. She still recalls waking up after the procedure and seeing other women crying out their husbands’ names in pain. In the following years, Josefa suffered from infections and cancer. Decades later, Josefa and others are still seeking justice through a class action suit against the ex-president. Follow: https://t.me/rtdocumentary

Hashtags

El Gourmet Urbano

@gourmeturbano · Post #20608 · 02.08.2025 г., 14:24

#GASTRONOMIA#VENEZUELA#PERU👩🏻‍🍳🧑🏻‍🍳👨🏻‍🍳 | Chef venezolano triunfa con restaurante peruano en su país: "Necesitaba de la gastronomía de Perú" https://ift.tt/YdZC8u1 August 02, 2025 at 09:15AM

ПретходнаСтраница 1 од 4Следна