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 слични објави

Пребарај: #democratic

当前筛选 #democratic清除筛选
Embassy of Russia in Singapore

@rusembsg · Post #3846 · 10.02.2025 г., 03:34

On the occasion of the Russian #DiplomatsDay (February 10) we would like to tell you about the Contribution of Soviet Diplomacy to the Establishment of the #UN Key points: - At the #Moscow Conference of the Ministers of Foreign Affairs of the USSR, USA, Great Britain and China in October 1943, the #Soviet delegation put forward a proposal to establish a universal international organization. - The first draft of the #UNCharter was developed at a conference convened at the suggestion of the #USSR in Dumbarton Oaks (#USA) from September 21 to October 7, 1944. At this forum, representatives of the USSR, the USA, #GreatBritain and #China agreed on the goals, structure and functions of the world organization. The Soviet delegation consistently and resolutely advocated that the activities of this organization be based on democratic principles. - At the #Crimea (Yalta) Conference of the leaders of the great powers, which took place from 4 to 11 February 1945, participants agreed upon the issues of the initial members of the organization and the voting procedure in the Security Council, as well as on issues related to the maintenance of international peace and security, the development of economic relations, cooperation in the social, technical and other areas of interstate relations. - On April 25 – June 26, 1945, the founding conference of the United Nations was held in #SanFrancisco. The Soviet delegation sought to ensure that the #democratic principles of the structure and activities of the UN were enshrined in the Charter. - Based on Soviet amendments, important new provisions were included in the chapter on the purposes and principles of the UN, stating that peaceful settlement of international disputes should be carried out "in accordance with the principles of justice and international law"; that friendly relations between nations should develop "on the basis of respect for the principle of equal rights and self-determination of peoples"; that international cooperation in resolving international problems of an economic, social, cultural and humanitarian nature should be carried out "and in promoting and encouraging respect for human rights and for fundamental freedoms for all without distinction as to race, sex, language or religion...". - On June 26, 1945, the UN Charter was signed by A.A. Gromyko, then the Soviet Ambassador to the USA, thanks to whose personal participation and persistence the final documents related to the creation of the UN recorded positions largely corresponding to the interests of the Soviet Union. Full article: https://telegra.ph/te4st-02-10