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

Резултати

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

Пребарај: #archaeology

当前筛选 #archaeology清除筛选
Amazing Geography 🌍

@amazingeo · Post #143 · 30.08.2025 г., 09:12

🌍 Machu Picchu in Peru was built atop a mountain ridge by the Incas around 1450. Its stone walls fit together so precisely that some areas withstand earthquakes without mortar. ✨ #heritage⚡#archaeology⚡#mountains⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍 ​

Amazing Geography 🌍

@amazingeo · Post #679 · 01.04.2026 г., 20:31

🌍 Machu Picchu in Peru is a heritage site set amid mountain peaks and cloud forests. Its stone terraces and temples blend ancient Inca engineering with dramatic natural scenery. ✨ #heritage⚡#archaeology⚡#landscape⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40688 · 21.02.2026 г., 15:00

A gold coin found in 1713 in Transylvania is likely genuine. The coin shows a Roman ruler named Sponsian, who was long believed to be fictional. Tests found real ancient wear and soil deposits, suggesting he was a real leader during the 3rd-century Roman crisis. 🪙🏛️ [Read more] @googlefactss #history#ancientrome#archaeology#facts

Amazing Geography 🌍

@amazingeo · Post #485 · 30.11.2025 г., 12:31

🌍 The ancient city of Angkor in Cambodia covered more land than any other pre-industrial city, with a vast network of canals and reservoirs that shaped both its culture and the landscape for centuries. ✨ #historicalgeography⚡#archaeology⚡#settlement⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #678 · 31.03.2026 г., 20:31

🌍 The lost city of Cahokia once stood near present-day St. Louis, with earthen mounds and a population rivaling European cities around 1100 CE—making it North America’s largest urban center before Columbus. ✨ #historicalgeography⚡#archaeology⚡#civilization⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1326 · 03.03.2026 г., 22:11

🌎 In the Nevada desert, the 2,000-year-old Lovelock Cave yielded mysterious oversized sandals, giant bones, and duck decoys. While duck decoys are confirmed as Native American artifacts, reports of giant bones and massive sandals remain unverified, fueling legends of a lost tribe. Archaeologists still debate the origins and meaning of these unusual finds. ✨ #history⚡#archaeology⚡#mystery 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1251 · 24.01.2026 г., 12:11

🌎 The disappearance of the 1,200-year-old Maya city of El Mirador remains an unsolved mystery. Once a major metropolis with vast pyramids in Guatemala, it was suddenly abandoned around 150 CE. Archaeologists have not found evidence of war, plague, or fire to explain why its tens of thousands of residents left so abruptly. ✨ #history⚡#archaeology⚡#mystery 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1225 · 15.01.2026 г., 18:11

🌎 The disappearance of the Ninth Roman Legion, Legio IX Hispana, remains one of history’s greatest unsolved mysteries. Records show the legion vanished from Roman chronicles after around 120 CE in Britain. Despite searches, no definitive evidence of its fate or mass grave has ever been found. ✨ #history⚡#mystery⚡#archaeology 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #962 · 24.10.2025 г., 22:11

🌎 The mysterious ancient city of Great Zimbabwe was built using massive stone walls without mortar, yet no written records explain how its builders achieved such precise engineering. Archaeologists estimate the complex appeared between the 11th and 15th centuries and covers over 7 square kilometers. ✨ #history⚡#archaeology⚡#mystery 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #886 · 10.10.2025 г., 12:11

🌎 In 2014, archaeologists uncovered a set of 2,000-year-old Roman lead tablets in a well in Britain. These inscribed tablets feature curses, prayers, and personal wishes, puzzling researchers with unusual languages and names not seen in surviving Roman texts. Over 130 of these "curse tablets" were recovered from the site in Bath. ✨ #archaeology⚡#mystery⚡#history 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #862 · 05.10.2025 г., 15:11

🌎 The lost city of Ubar, often called the "Atlantis of the Sands," is a legendary ancient settlement thought to be buried under Oman’s deserts. Satellite imagery and excavations in the 1990s revealed buried structures at Shisr, but no proof has confirmed Ubar’s identity or vast wealth described in Arabian lore. ✨ #history⚡#mystery⚡#archaeology 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #817 · 26.09.2025 г., 15:11

🌎 The disappearance of the English colony at Roanoke Island in the late 16th century remains unsolved. When resupply ships arrived in 1590, the settlers were gone, with "CROATOAN" carved into a post as the only clue. Archaeologists have found no definitive evidence, and the fate of over 100 people is still a mystery. ✨ #history⚡#archaeology⚡#mystery 👉subscribe Interesting Planet 👉more Channels ​

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