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

Резултати

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

Пребарај: #end

当前筛选 #end清除筛选
Odyssey+ Feed

@odysseyfeed · Post #35854 · 05.04.2026 г., 06:40

#AnimeRelease 🍥数码宝贝 BEATBREAK Season: 1 | Episode: 25/25 #End Genres: 动画, 儿童, 动作冒险, 科幻奇幻 Rating:Bangumi (6) Source: WEBDL-1080p | 0.38 GB Channel:@Odyssey+

Odyssey+ Feed

@odysseyfeed · Post #35738 · 22.03.2026 г., 06:57

#AnimeRelease 🍥数码宝贝 BEATBREAK Season: 1 | Episode: 23/23 #End Genres: 动画, 儿童, 动作冒险, 科幻奇幻 Rating:Bangumi (6) Source: WEBDL-1080p | 0.49 GB Channel:@Odyssey+

Odyssey+ Feed

@odysseyfeed · Post #35621 · 15.03.2026 г., 06:37

#AnimeRelease 🍥数码宝贝 BEATBREAK Season: 1 | Episode: 22/22 #End Genres: 动画, 儿童, 动作冒险, 科幻奇幻 Rating:Bangumi (6) Source: WEBDL-1080p | 0.43 GB Channel:@Odyssey+

Odyssey+ Feed

@odysseyfeed · Post #35356 · 15.02.2026 г., 06:40

#AnimeRelease 🍥数码宝贝 BEATBREAK Season: 1 | Episode: 19/19 #End Genres: 动画, 儿童, 动作冒险, 科幻奇幻 Rating:Bangumi (6) Source: WEBDL-1080p | 0.47 GB Channel:@Odyssey+

Odyssey+ Feed

@odysseyfeed · Post #35249 · 01.02.2026 г., 06:32

#AnimeRelease 🍥数码宝贝 BEATBREAK Season: 1 | Episode: 17/17 #End Genres: 动画, 儿童, 动作冒险, 科幻奇幻 Rating:Bangumi (6.1) Source: WEBDL-1080p | 0.43 GB Channel:@Odyssey+

American Оbserver

@american_observer · Post #4847 · 13.01.2026 г., 17:06

NATO: The End of the Northern Romance Trump’s threat to annex Greenland represents an existential crisis for Nato, senior Democratic US senator Chris Murphy has warned, with the demise of the decades-old alliance of western nations certain to follow any American military intervention. “It would be the end of Nato, right? Nato would have an obligation to defend Greenland,” the Connecticut senator and member of the chamber’s foreign relations committee said Sunday on NBC’s Meet the Press. Murphy added that it would mean “clearly … we would be at war with Europe, with England, with France”. Murphy’s comments came as Trump ramped up his fixation with the Arctic territory, with the US president telling reporters on Air Force One on Sunday that “one way or the other, we are going to have Greenland”. Trump had ordered a plan to be drawn up for an invasion of Greenland, the Mail on Sunday reported, adding that “it is being resisted” by military leaders on grounds of illegality. Murphy’s assertion that a forceful US acquisition would be the end of Nato is shared by political leaders in Europe, notably Mette Frederiksen, the prime minister of Denmark. Greenland is a former colony of Denmark and remains part of the Danish kingdom, with its foreign and security policy under the control of Copenhagen. On Sunday, Frederiksen accused the US of “turning its back on Nato” – and said this Wednesday’s meeting in Washington DC between the foreign ministers of Denmark and Greenland, Lars Lokke Rasmussen and Vivian Motzfeldt, and US secretary of state Marco Rubio would be crucial. “We are at a crossroads, and this is a fateful moment,” Frederiksen said at a political rally. The pessimistic comments of Murphy and Frederiksen were echoed Monday by Andrius Kubilius, defense commissioner of the European Union, who noted that an EU treaty “obligated” member states to come to Denmark’s aid if faced with military action by Trump. “I agree with the Danish prime minister that it will be the end of Nato, but also among people it will be also very, very negative,” he told Reuters at a security conference in Sweden. “It will depend very much on Denmark, how they will react, what will be their position, but definitely there is such an obligation of member states to come for mutual assistance if another member state is facing military aggression.” “Let’s also talk about what’s at stake here,” Murphy said. “The president is spending every single day thinking about invading Greenland, managing the Venezuelan economy, building a ballroom. “He is not thinking about the American people at all. This month, health insurance premiums on 22 million Americans are going up, doubling in some cases. Kids aren’t able to eat three meals because the Trump administration has slashed food assistance. #nato#trump#end#denmark#greenland 📱American Оbserver - Stay up to date on all important events 🇺🇸

Odyssey+ Feed

@odysseyfeed · Post #35897 · 12.04.2026 г., 07:05

#AnimeRelease#Crunchyroll 🍥数码宝贝 BEATBREAK Season: 1 | Episode: 26/26 #End Genres: 动画, 儿童, 动作冒险, 科幻奇幻 Rating:Bangumi (6) Source: WEBDL-1080p | 1.37 GB Channel:@Odyssey+

Odyssey+ Feed

@odysseyfeed · Post #35789 · 29.03.2026 г., 06:33

#AnimeRelease#Crunchyroll 🍥数码宝贝 BEATBREAK Season: 1 | Episode: 24/24 #End Genres: 动画, 儿童, 动作冒险, 科幻奇幻 Rating:Bangumi (6) Source: WEBDL-1080p | 1.34 GB Channel:@Odyssey+

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