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

Резултати

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

Пребарај: #tanzania

当前筛选 #tanzania清除筛选
Voyage.Travel.Tourism

@VOYAGE · Post #1402 · 26.04.2025 г., 12:14

🌴💖Zanzibar – the pearl of Tanzania and one of the best beach destinations in the Indian Ocean 📏 📏 📏 📏 📏 📏 📏 📏 #Tanzania🇹🇿@voyage

Hashtags

Voyage.Travel.Tourism

@VOYAGE · Post #1189 · 08.12.2024 г., 13:14

Zanzibar – The Jewel of Tanzania and one of the best beach destinations in the Indian Ocean. 🌴💖 📏 📏 📏 📏 📏 📏 📏 📏 #Tanzania🇹🇿 @voyage

Hashtags

Voyage.Travel.Tourism

@VOYAGE · Post #1079 · 31.08.2024 г., 12:14

🗺Tanzania🇹🇿 Zanzibar is Africa's Maldives, a place on the map with dozens of breathtakingly beautiful beaches! Pristine white sand, turquoise Indian Ocean waters, gentle sunshine, and fewer crowds make it an ideal vacation spot. #Tanzania @voyage

Hashtags

RTDocumentary

@rtdocumentary · Post #215 · 16.09.2021 г., 11:45

Crawling up Kilimanjaro with no legs #video#Tanzania When Aleksandr was born with no legs and deformed fingers, his mother abandoned him. He grew up in an orphanage for kids with disabilities in a remote Russian town. However, Aleksandr has always aimed high and dreamed big. Aleksandr got lucky and was selected to take part in a US humanitarian project. At the age of 15, he walked on his new prostheses for the first time in his life. His temporary foster parents couldn’t let him go and adopted Aleksandr. To inspire kids with disabilities, Aleksandr and his friends from the orphanage took on the challenge to climb Africa’s highest mountain Mount Kilimanjaro at 5,895 metres. RT Documentary witnessed their incredible feat and made a film - https://youtu.be/v2Sz3k9gKp8 For now, Aleksandr lives and studies in Boston, USA, and has climbed Kilimanjaro for a second time! Follow: https://t.me/rtdocumentary

ጠቅላይ ሚኒስትር ዐቢይ አሕመድ (ዶ/ር) ከታንዛኒያ ዩናይትድ ሪፐብሊክ ፕሬዝዳንት ጋር ተወያዩ ******************* ጠቅላይ ሚኒስትር ዐቢይ አሕመድ (ዶ/ር) ከታንዛኒያ ዩናይትድ ሪፐብሊክ ፕሬዝዳንት ሳሚያ ሱሉህ ሀሰን ጋር ተወያይተዋል፡፡ ጠቅላይ ሚኒስትሩ በማህበራዊ ትስሰር ገጻቸው ባጋሩት መልእክት፤ ከታንዛኒያ ዩናይትድ ሪፐብሊክ ፕሬዝዳንት ሳሚያ ሱሉህ ሀሰን ጋር የሁለትዮሽ ግንኙነትን በሚያጠናክሩ አስቻይ ጉዳዮች ላይ ውይይት አድርገናል ብለዋል:: #EthiopianBroadcastingCorporation#Ebcdotstream#Ethiopia#PMAbiy#Tanzania#Diplomacy

RTDocumentary

@rtdocumentary · Post #770 · 15.05.2022 г., 18:02

‘Isaac is a very fast and intelligent rat. He is good at concentrating on finding TNT.’ In Tanzania, giant hamster rats are trained to be professional bomb disposal experts. They work in minefields in former hotspots. The rodents can easily smell carefully camouflaged explosive devices thanks to their excellent sense of smell. Do you want to see how a bomb-sniffing rat is trained? Then, watch the clip and film Isaac: The Story of a Little Giant. #Tanzania#minefields Follow: https://t.me/rtdocumentary

AREA

@area_eng · Post #115 · 22.06.2025 г., 14:03

Russia and Tanzania are developing cooperation in nuclear energy During the negotiations at SPIEF-2025, Russian Energy Minister Sergei Tsivilev and Tanzanian Deputy Prime Minister and Minister of Energy Biteko Doto Mashaka discussed the prospects for joint work in the energy sector. The Tanzanian side presented an ambitious five-year energy development program, which provides for a gradual increase in electricity supply to the population from current levels to 75%, and in the future - up to 100% coverage. Particular attention in the strategy is paid to the development of renewable energy sources and the study of the possibilities of peaceful nuclear energy. "Our president set the task that it is impossible to build technological sovereignty in one separate country. It must be built together with friendly countries. And the Republic of Tanzania is precisely our friendly country. Therefore, we are ready to share our technologies," Sergei Tsivilev emphasized. The Russian side proposed a comprehensive approach to cooperation. It includes the possible construction of low-power nuclear power plants, training of personnel in Russian universities, conducting technical and economic research, as well as implementing joint projects in non-energy areas - medicine and agriculture. This dialogue has become a logical continuation of previously reached agreements. In April 2025, Rosatom and the Ministry of Energy of Tanzania signed a memorandum on cooperation in the field of non-energy application of nuclear technologies. New negotiations expand the scope of interaction, opening up prospects for the implementation of large-scale energy projects. Experts note that Russian-Tanzanian cooperation in the nuclear sector can become a key factor in the implementation of the energy strategy of the African country. It will provide its population with stable and environmentally friendly energy sources, and will also create a basis for the technological development of a number of related sectors of the economy. #AREA#Africa#Russia#Tanzania#energy

RTDocumentary

@rtdocumentary · Post #749 · 12.05.2022 г., 15:00

'My father needed cows, not me'. These are the words of 13-year-old Kristina from Tanzania. Her father sold her to an older man to get a cow. The tradition is still widespread in Tanzania. Families live in poverty and find it difficult to feed themselves. So for a 13-year–old bride, her parents receive a rich dowry - almost a herd of cows. But the Tanzanian government is cracking down on this custom. Watch Kristina’s heartbreaking story. You can learn more about this tradition in ourfilm Bride Trade. #Tanzania#traditions#bridetrade Follow: https://t.me/rtdocumentary

123•••56
ПретходнаСтраница 1 од 6Следна