@telelakel · Post #886 · 01.03.2026 г., 10:44
🤖 Telegram Bot API updated to v9.5 https://core.telegram.org/bots/api-changelog#march-1-2026 @telelakel
Hashtags
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
Пребарај: #march
@telelakel · Post #886 · 01.03.2026 г., 10:44
🤖 Telegram Bot API updated to v9.5 https://core.telegram.org/bots/api-changelog#march-1-2026 @telelakel
Hashtags
@Dailyrss · Post #13304 · 31.03.2026 г., 00:45
Wikipedia每日一图(#March 31, 2026)https://ift.tt/vOFu0pT Viking Sky (ship, 2017) - moored in the harbour of Sète (Hérault, France). 了解更多 . #Wikipedia每日一图
Hashtags
@Dailyrss · Post #13303 · 30.03.2026 г., 00:45
Wikipedia每日一图(#March 30, 2026)https://ift.tt/jKRlxtY Sand dunes of the Thar Desert in the Indian state of Rajasthan. On this day in 1949, the state was formed after a merger of several Rajput princely states into the Indian Union following India's independence from British colonial rule.. 了解更多 . #Wikipedia每日一图
Hashtags
@Dailyrss · Post #13302 · 29.03.2026 г., 00:45
Wikipedia每日一图(#March 29, 2026)https://ift.tt/57A9c2T Sunrise in Pieniny mountains, Poland. 了解更多 . #Wikipedia每日一图
Hashtags
@Dailyrss · Post #13301 · 28.03.2026 г., 00:45
Wikipedia每日一图(#March 28, 2026)https://ift.tt/Q2Tc4Lz Mary Martin with children, during production of the Broadway musical The Sound of Music. Martin portrayed Maria von Trapp who died on this day in 1987.. 了解更多 . #Wikipedia每日一图
Hashtags
@Dailyrss · Post #13300 · 27.03.2026 г., 00:45
Wikipedia每日一图(#March 27, 2026)https://ift.tt/hF6YJ9b Northern lights in the night sky over Mývatn, Iceland.. 了解更多 . #Wikipedia每日一图
Hashtags
@Dailyrss · Post #13299 · 26.03.2026 г., 00:45
Wikipedia每日一图(#March 26, 2026)https://ift.tt/NlEYxdD Kyzylkup table mountain. Kyzylsai regional park, Mangystau District, Mangystau Region, Kazakhstan. 了解更多 . #Wikipedia每日一图
Hashtags
@Dailyrss · Post #13298 · 25.03.2026 г., 00:45
Wikipedia每日一图(#March 25, 2026)https://ift.tt/lAHLyPt Villages of Hullathy Gram Panchayat in a steep arid valley in the north face of the Nilgiri Mountains. Villagers have created a vibrant agrarian economy, largely vegetables and tea, using terraces and irrigation. Tamil Nadu, India.. 了解更多 . #Wikipedia每日一图
Hashtags
@Dailyrss · Post #13297 · 24.03.2026 г., 00:45
Wikipedia每日一图(#March 24, 2026)https://ift.tt/YleAf4m Little corella (Cacatua sanguinea gymnopis) Murray River, Blanchetown, South Australia. A type of cockatoo.. 了解更多 . #Wikipedia每日一图
Hashtags
@Dailyrss · Post #13296 · 23.03.2026 г., 00:45
Wikipedia每日一图(#March 23, 2026)https://ift.tt/EHIGf8M A previously unpublished illustration intended for the Saturday Evening Post's 1943 New Year's edition. It was never used due to publisher demands that the illustrator, J.C. Leyendecker, create a more optimistic and patriotic cover that was sensitive to the families of American soldiers. It was publicly shown for the first time in 2020 as part of an auction.. 了解更多 . #Wikipedia每日一图
Hashtags
@Dailyrss · Post #13295 · 22.03.2026 г., 00:45
Wikipedia每日一图(#March 22, 2026)https://ift.tt/EdkunCs Royal angelfish (Pygoplites diacanthus), Ras Muhammad National Park, Red Sea, Egypt. The body of the royal angelfish is moderately elongate, is very compressed and can reach a length of up to 25 centimetres (9.8 in) It's widely distributed throughout the Indo-Pacific and can be found in the Red Sea and Indian Ocean around East Africa and the Maldives, stretching to the Tuamoto Islands, New Caledonia, and Great Barrier Reef. The royal angelfish occurs at depths ranging from 0 to 80m (0 to 262 ft), in coral rich areas of lagoons, reefs, and are also often found in the vicinity of caves. It is a carnivorous species that feeds on sponges and tunicates located throughout reefs and underwater caves. They are a non-migratory species that can be found solitary, in pairs, or groups. Probably the most spectacular fish I've ever seen underwater in terms of colors. we have no FPs of the whole family Pomacanthidae (marine angelfishes).. 了解更多 . #Wikipedia每日一图
Hashtags
@Dailyrss · Post #13294 · 21.03.2026 г., 00:45
Wikipedia每日一图(#March 21, 2026)https://ift.tt/VAFcWl0 Morning in a Pine Forest (1889) by Russian artists Ivan Shishkin and Konstantin Savitsky.. 了解更多 . #Wikipedia每日一图
Hashtags