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

Резултати

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

Пребарај: #marriage

当前筛选 #marriage清除筛选
RTDocumentary

@rtdocumentary · Post #790 · 19.05.2022 г., 16:01

'There are never kisses at weddings. We will start talking to each other in a month or so'. These are the words of the Kalderash Gypsy Andrei, who was married at 12. When he turned ten, his parents started looking for a young bride. Child marriage is common in Roma villages. Whether the kids want it or not, no one asks. Watch Andrei's story in our video. What goes on inside this unusual culture? Check out the film Romany Romance. #video#marriage Follow: https://t.me/rtdocumentary

Pensive|

@PensivePost · Post #5148 · 29.04.2021 г., 09:53

Marriage Describing life without marriage is not possible. At the right age, we do marriages if you don't want to marry people judge you differently, human is social animals. We need each other's help, this help may be for physical satisfaction or following culture and rules by the family. As you know two types of marriages happen all around the world first one is love marriage or 2 arrange marriage. I don't need to tell you about both you are aware of those things even in simple lines I would like to describe it. 1. Love marriage Love happens in school or colleges where we see new, new faces and characters. That attracts us their style of talking, face, spot or writing bla. bla... We can not fall in love exactly by one accident we fall in love by our habits and wishes match to each other and when we help each other. Many authors have described love in many forms. Love is always standing separately from any other subjects. Don't waste your life in love. You will get many people to tell you like this but what is there without love. Love gives you happiness and sadness, joy and gloom, daring and fear, respect and disesteem, victor and failure. Someone has said everything is possible in love and war. You can lose your mind and become crazy. I have not fallen in love yet it's my weakness and strength. I don't want to marry and fall in love. Because I'm not able to handle them they used to talk very silly. They are not crazy, they made to make us crazy. 2. Arrange Marriage. Doing arrangement means preparation. It goes with rules and customs if you are old-fashioned or believe in that custom you go through every single step. But nobody is following those rules. We can't stop ourselves to be quiet until the marriage ceremony. We talk on call after the first meeting And take two-three times kisses after fixed marriage we want a separate place to talk. Here everything is under the control of your elders. You know this life is not goes all the time as you think. Enjoy every aspect of life that is life. Either love marriage or arrange marriage. #review#article#marriage

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40244 · 03.12.2025 г., 15:00

Early Roman brides carried a bunch of herbs, like garlic and rosemary 🌿, under their veils to symbolize fidelity ❤️ and fertility 🌱, and to ward off evil 🛡️. These herbs were the precursor to the modern bridal bouquet 💐. @googlefactss#history#marriage#europe [read more...]

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40627 · 05.02.2026 г., 07:01

"Dekichatta kekkon" (できちゃった結婚) or "dekikon" is a Japanese slang from the late 1990s. It means a marriage due to unplanned pregnancy, like a "shotgun wedding," which is a quick marriage to accept an unplanned pregnancy, named after a father using a shotgun to encourage marriage. 📅🤰💍 [Read More] @googlefactss #Japan#Marriage#Slang#Pregnancy#Facts

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40899 · 04.04.2026 г., 22:01

In parts of Togo, wedding ceremonies include the groom’s family performing dances and music. These performances show respect to the bride’s family and celebrate the upcoming marriage. The events often involve drumming, singing, and group dancing as part of the traditional festivities. 💃🥁💍🌍 [Read more] @googlefactss #marriage#culture#tradition#worldfacts#anthropology#africa#weddingrituals#travel If you have ideas or feedback contact us: @Googlefactss_Feedback_bot

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40839 · 21.03.2026 г., 23:01

In certain Thai weddings, couples participate in the Sai Sin ritual, a sacred tradition rooted in Buddhist beliefs. A cotton thread, called Sai Sin, is blessed by monks before the ceremony. The thread is tied around the bride and groom’s wrists or connected around their heads. This ritual symbolizes protection, good luck, and spiritual blessings for the couple. Guests and family may also touch or tie pieces of the thread to pass on their blessings. The Sai Sin connects the newlyweds to their family, community, and the monks who bless them, emphasizing unity and shared support. It is often performed alongside other traditional Thai wedding customs like pouring holy water over the hands of the bride and groom. 🧵👰🤵🇹🇭 [Read more] @googlefactss #marriage#culture#tradition#worldfacts#anthropology#thailand#weddingrituals#travel

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40872 · 28.03.2026 г., 23:01

In some Mexican weddings, couples participate in the Lazo ritual. A large cord or rosary is placed around the bride and groom in a figure-eight shape to symbolize unity and lifelong commitment. 🤍👰🤵🇲🇽 [Read more1] [Read more2] @googlefactss #marriage#culture#tradition#worldfacts#anthropology#mexico#weddingrituals#travel