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

Резултати

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

Пребарај: #mufc

当前筛选 #mufc清除筛选
Manchester United⚽💯

@manchester_utdfc · Post #115159 · 15.05.2026 г., 14:16

Matthijs de Ligt: “Since November I have done everything, pushing myself in every session and exploring every option, to get back to doing what I love, playing football. “I am grateful to everyone who has supported me throughout a difficult period in my career. I remain as determined as ever to represent Manchester United and play in front of our incredible supporters as soon as possible.” #MUFC [MU]

Hashtags

Manchester United⚽💯

@manchester_utdfc · Post #115158 · 15.05.2026 г., 14:12

Matthijs de Ligt Ig: “After 6 months of treatment and working hard to get back, surgery was the only option left. I’m disappointed I couldn’t help the team the last 6 months and obviously missing out on the World Cup but I am looking forward to doing everything to get back in front of the fans and feeling better again 🙏🏼💪🏼” #MUFC

Hashtags

Manchester United⚽💯

@manchester_utdfc · Post #115157 · 15.05.2026 г., 14:11

Matthijs de Ligt has undergone successful surgery to adress a back injury, say Manchester United. They say De Ligt will begin a new phase of his recovery and is expected to return for United in the early stages of the 2026/27 season. #MUFC

Hashtags

Manchester United⚽💯

@manchester_utdfc · Post #115156 · 15.05.2026 г., 14:04

Michael Carrick has ACCEPTED #mufc's contract proposal! He will sign as head coach until 2028, with the option to extend for another season. 𝐇𝐄𝐑𝐄 𝐖𝐄 𝐆𝐎 ✅🏴󠁧󠁢󠁥󠁮󠁧󠁿 [Fabrizio Romano]

Hashtags

Manchester United⚽💯

@manchester_utdfc · Post #115155 · 15.05.2026 г., 13:14

Michael Carrick on #mufc's future targets: "You’ve got to aim upwards. That’s the beauty of football, beauty of competition to achieve something and back it up, that’s the challenge. "For the players, for the squad, for the whole group and football club we want to keep moving in a positive way and in the right direction. "The closer you get to the top the less room for progress, but progress is what we’re aiming for."

Hashtags

Manchester United⚽💯

@manchester_utdfc · Post #115148 · 15.05.2026 г., 11:09

Jamie Carragher on his ‘leave football before it leaves you’ comments on Casemiro: “In retrospect, do I regret my comments about such a legendary footballer? Yes and no. It must be acknowledged that the implication that Casemiro was 'finished' at the highest level was too harsh and premature. “My argument was he would be better heading out to the MLS, or accepting offers from Saudi Arabia, because he would never get back to anywhere near his best to achieve the same heights of winning the Champions League or league titles at Old Trafford as he did so brilliantly at Real Madrid. “At the time, those observations were not controversial. In 2024, Casemiro was unfit, lacked the physicality and athleticism to cope with quicker, sharper opponents, and was exposed when used in a deeper role, either in midfield or at centre-back as he was that night at Selhurst Park. “This week, Casemiro suggested my remarks were 'disrespectful', and that is fair enough. Anything he says in response comes with the territory, although I would counter and say no disrespect was intended. Quite the contrary. “Because of his stellar career, it was natural to compare Casemiro to the extraordinarily high standards he set for himself.” #MUFC [Telegraph] 📥@Manchester_Utdfc

Hashtags

Manchester United⚽💯

@manchester_utdfc · Post #115143 · 15.05.2026 г., 10:51

🚨 Manchester United are proposing an initial TWO-YEAR contract offer to Michael Carrick until 2028! Talks are now underway after co-owner Sir Jim Ratcliffe gave the go-ahead following an executive committee meeting this week where chief executive Omar Berrada and director of football Jason Wilcox made the recommendation for Carrick to get the job full-time 🔴 [Laurie Whitwell, The Athletic] #mufc 📥@Manchester_Utdfc

Hashtags

Manchester United⚽💯

@manchester_utdfc · Post #115142 · 15.05.2026 г., 10:46

Michael Carrick’s backroom staff are expected to stay, with Steve Holland, Jonathan Woodgate and Jonny Evans all in line for new deals. Craig Mawson is also set to continue as first-team goalkeeping coach following his promotion after Ruben Amorim’s departure. #mufc also want to add a set-piece coach, with Andreas Georgson, highly rated during his previous spell at United, among the contenders to return from Tottenham [Laurie Whitwell] 📥@Manchester_Utdfc

Hashtags

Manchester United⚽💯

@manchester_utdfc · Post #115135 · 15.05.2026 г., 08:35

Bruno Fernandes: “I’ve always said, Declan Rice was a player to play for #mufc, I was really sad when he chose to go Arsenal. “I always thought he would be a PERFRCT fit for our club.” 📥@Manchester_Utdfc

Hashtags

Manchester United⚽💯

@manchester_utdfc · Post #115132 · 14.05.2026 г., 13:41

Excl: #MUFC plan to offer Michael Carrick an initial contract of 2 years until June 2028 with a 1 year option to extend. No formal negotiations have begun so no agreement yet. The 44 yo has been involved in recruitment meetings for the summer. [Sully Talkz] 📥@Manchester_Utdfc

Hashtags

123•••10•••1617
ПретходнаСтраница 1 од 17Следна