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

Резултати

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

Пребарај: #geography

当前筛选 #geography清除筛选
Language Trivia 🤔

@languagetrivia · Post #301 · 09.11.2024 г., 17:57

Gibraltar is a small territory located on the southern coast of the Iberian Peninsula, on the Mediterranean Sea. It is bordered by Spain to the north and sits at the entrance of the Strait of Gibraltar, which separates Europe from Africa. Known for its iconic Rock of Gibraltar, this territory has a unique geographic and cultural identity. What is the official language of Gibraltar? • A) Spanish • B) English • C) Andalusian Arabic • D) Portuguese Press ❤️ Follow @languagetrivia for more fun facts! #geography#guess_the_language

The Salzkammergut is a region in Austria, mostly frequented for relaxation vacation, hiking and climbimg. It stretches from the city of Salzburg eastwards to the Dachstein Mountains. The historic city of Hallstatt is located in the Salzkammergut, giving name to the Hallstatt culture, the predominant Western and Central European culture of the late Bronze Age from the 12th to 8th centuries BC and early Iron Age from the 8th to 6th centuries BC. #geography#history @EuropeanTribalism

Language Trivia 🤔

@languagetrivia · Post #123 · 04.10.2024 г., 17:20

What is one of the two official languages of Macau, a region of China often referred to as the 'Las Vegas of the East'? 🧠 Join @languagetrivia for more fascinating questions #guess_the_language#image#geography Check out the correct answer in the comment

Interesting Planet 🌍

@interesting_planet_facts · Post #1298 · 17.02.2026 г., 22:11

🌎 Along the India-Bangladesh border, a cluster of over 160 tiny enclaves once existed, creating a patchwork of territories within territories. Before a 2015 land swap, some villages belonged to India but were completely surrounded by Bangladesh, and vice versa, forming the world’s most complex international border tangle. ✨ #borders⚡#geography⚡#history 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1202 · 07.01.2026 г., 22:11

🌎 Baarle-Hertog and Baarle-Nassau, two towns in Belgium and the Netherlands, form one of the world’s most complex borders, with 26 separate enclaves and counter-enclaves interlocking like a puzzle. Some houses are split between countries, with the nationality determined by the location of the front door. ✨ #geography⚡#borders⚡#history 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1115 · 09.12.2025 г., 22:11

🌎 The border between India and Bangladesh features over 160 enclaves and counter-enclaves—small pockets of land belonging to one country inside the other. Before a 2015 land swap, Dahala Khagrabari was the world’s only third-order enclave: an Indian village inside a Bangladeshi enclave, within an Indian enclave, inside Bangladesh. ✨ #borders⚡#geography⚡#history 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1083 · 29.11.2025 г., 12:11

🌎 Few borders are stranger than the Haskell Free Library and Opera House, built in 1904 directly on the US-Canada line. The building straddles Derby Line, Vermont, and Stanstead, Quebec, with a black line on the floor marking the international boundary. Its reading room is in the US, but most books are in Canada. ✨ #borders⚡#geography⚡#history 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1051 · 18.11.2025 г., 22:11

🌎 Strange borders divide the island of Cyprus: the capital, Nicosia, is split by the "Green Line," a UN-controlled buffer zone between Greek and Turkish Cypriot sectors. This boundary cuts through streets and buildings, creating the world’s last divided capital city. ✨ #borders⚡#geography⚡#history 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1012 · 07.11.2025 г., 12:11

🌎 The divided town of Baarle straddles the border between Belgium and the Netherlands in a tangled patchwork of enclaves. Some houses are split by the boundary, so front doors determine which country's laws apply. This border complexity results from medieval land deals, with 22 Belgian and 8 Dutch enclaves in total. ✨ #borders⚡#geography⚡#history 👉subscribe Interesting Planet 👉more Channels ​

123•••5•••10•••15•••20•••25•••30•••35•••40•••45•••50•••55•••60•••6364
ПретходнаСтраница 1 од 64Следна