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

Резултати

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

Пребарај: #mgimo81

当前筛选 #mgimo81清除筛选

🌐 Today marks the 81st anniversary of the founding of the Moscow State Institute of International Relations!Congratulations to all – alumni, students, professors, and friends of the university – on the birthday of their beloved alma mater! 📜Historical background: 81 years ago, on October 14, 1944, the People’s Commissariat for Foreign Affairs of the USSR, headed by Vyacheslav Molotov, decided to establish a specialized educational institution for diplomatic training. In the final years of the Great Patriotic War, it became clear that the Soviet Union needed a new generation of professionals for its foreign service. The growing number of international contacts and negotiations on the post-war world order required highly qualified experts fluent in foreign languages, as well as in history, law, and economics. Such specialists were also needed for work in international organizations that were being planned after the war – above all, the United Nations and its affiliated bodies. 🌍In 1946, #MGIMO opened its doors to foreign students, laying the foundation for its international academic reputation. Since then, it has become one of Russia’s most international universities: today, students from more than 90 countries study here, and foreigners make up about 16% of the total student community. In 2025 alone, 400 students from 55 countries enrolled in the freshmen year. Last year, Russia’s leading university specializing in international relations celebrated its 80th Anniversary – 👉#Recap. Over the decades of its active and fruitful work, MGIMO has rightfully earned its reputation as a world-class university – a genuine “foundry” of diplomats, journalists, and even presidents. 💬President of the Russian Federation Vladimir Putin: MGIMO has firmly established itself among the world’s leading centers for the training of international specialists. For many decades, its graduates have formed the professional “backbone” of Russia’s diplomatic service. Genuine professionalism also distinguishes MGIMO alumni working in other areas – in government agencies, academia, education, business, and the media. It is no coincidence that a MGIMO diploma is highly valued not only in Russia, but also abroad. 💬Foreign Minister of the Russian Federation Sergey Lavrov (MGIMO, Class of 1972): Diplomacy is the art of negotiation. The formation of a multipolar world is a long process that may take an entire historical era. MGIMO graduates will definitely have enough work to do. ✊We wish #MGIMO enduring prosperity, inspiration, and countless new triumphs! May the university always remain a place where the spirit of knowledge, friendship, and aspiration reigns – where every new generation of students feels pride in their alma mater, finds support, loyal friends, and their true calling! #MGIMO81