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

Резултати

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

Пребарај: #hockey

当前筛选 #hockey清除筛选
Main Event | Sport News

@maineventnews · Post #70 · 19.07.2024 г., 10:10

To participate in the Olympics, an Australian field hockey player amputated part of a broken finger instead of getting a cast and missing the Games. #Hockey 👁Subscribe to Main Event | Sport News

Hashtags

Main Event | Sport News

@maineventnews · Post #10 · 16.07.2024 г., 13:01

"We Lost a Child. The Support of Loved Ones and the Club Saved Us."#Hockey A Touching Farewell from the Canadian Superstar to Tampa Bay Steven Stamkos, after 16 years with the Tampa Bay Lightning, is leaving the team. This summer, he entered the free agency market and signed a four-year contract with the Nashville Predators. In a column on The Players' Tribune, the Canadian forward bid farewell to the club and the city where he became a star. Here is the translated material. This memory has been replaying in my head over the past few days. 7:30 AM. The day after our victory over Montreal, we had won our second Stanley Cup. The entire team was at my place. Parents, kids, partners, friends. No one had slept. We were all exhausted, but it was one of the best nights ever. We sat together, sharing joyful moments. We savored the moment. My son Carter got out of bed. He came down to the kitchen and made himself his favorite cereal for breakfast, only this time, he ate it from the Stanley Cup. I looked at him and thought, "Man, what a special moment this is..." I will remember this scene forever. Forever. 👁Subscribe to Main Event | Sport News

Hashtags

Trump's Ear

@trumpsear_tg · Post #2193 · 25.02.2026 г., 18:26

Hockey player Matthew Tkachuk gave the gold medal to Donald Trump. American hockey players met with President Donald Trump shortly before his address to Congress. Trump invited the athletes in a telephone conversation, which was organized from the locker room of the Olympic Games by FBI Director Kesh Patel. When Tkachuk handed over the award, Trump joked that he would not give it back. The U.S. national team won Olympic gold in men's hockey for the first time in 46 years. The last time the Americans won was so long ago — in 1980. In the deciding match on Sunday, February 22, 2026, the USA defeated Canada 2-1 in overtime. #Trump#Hockey 👂More on Trump's Ear ⚠️

Trump's Ear

@trumpsear_tg · Post #2186 · 24.02.2026 г., 15:59

The U.S. women's national hockey team refused to go to a meeting with Trump. The U.S. women's hockey team refused to attend the State of the Union ceremony, President Donald Trump's State of the Union address, NBC reported. 🏒 USA Hockey thanked the president for the invitation and noted that the team appreciates the attention. They won't be able to come because of their studies and work. The invitation came after Trump's joke. He called the men's team after the victory and said he would invite the women as well. He added that otherwise he could be impeached. The president's joke was considered inappropriate and downplayed the achievements of the women's national team. Immediately after the refusal, the national team accepted an invitation from rapper Flavor Flav to host a celebration in Las Vegas. However, it will be held only at the end of April, when the athletes' playing season ends. However, conservative media have already written that the hockey players preferred the rapper. 📺 #Trump#Hockey 👂More on Trump's Ear ⚠️

EdgeMarket.AI 📣

@edgemarketai · Post #8165 · 06.05.2026 г., 18:53

🏒 STANLEY CUP CONFERENCE FINAL New York Rangers vs Boston Bruins The road to the Stanley Cup continues. Two historic franchises face off in one of the biggest matchups of the season. Momentum, pressure, experience, intensity. Who advances? Make your prediction now on EdgeMarket: https://edgemarket.ai/bnb/ice-hockey/new-york-rangers-vs-boston-bruins/statistics/69f1dba4422739f6001fea43 #StanleyCup#NHLPlayoffs#Rangers#Bruins#EdgeMarket#SportsPredictions#AI#Hockey

Velvet Pages | eLibrary 🥂

@bookslibraryofficial · Post #1498 · 15.12.2025 г., 15:44

📖Title : Merry Little Kissmas ✍️Author : Lauren Blakely ⭐️Rating : 3.90/5 (Goodreads) 📆Published : Oct 28, 2025 ———————————————— Summary:In Merry Little Kissmas, a cheerful professional matchmaker takes on what should be an easy holiday job: finding a date for her brother’s grumpy best friend, a single-dad hockey player who hates Christmas. When he bets she can’t do it, she decides to fake-date him herself to prove she can. Set in the snowy small town of Evergreen Falls, their pretend romance includes Christmas competitions, tree farms, hot cocoa, and forced proximity. As playful banter turns into real intimacy, the hero’s guarded past slowly surfaces. By Christmas Eve, both must decide whether their growing feelings are just seasonal magic—or true love. ———————————————— #christmas#holiday#romance#audiobook#hockey#merrylittlekissmas#laurenblakely#sportsromance#contemporary@Bookslibraryofficial@free_novellas@eternalmantra

PROавтора Live

@proavtora · Post #203 · 27.08.2025 г., 09:19

🎙Повторный выпуск с Марком Барберио! На этот раз — полностью на его родном английском языке. Если тебе интересно послушать историю Марка без перевода или ты практикуешь английский — этот выпуск для тебя. 👉 Включай, смотри и прокачивай язык вместе с хоккейной историей. #PROавтора#podcast#madjozef#hockey#english#Barberio#Severstal#NHL#KHL#спорт#подкасты

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