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

Резултати

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

Пребарај: #cos2025

当前筛选 #cos2025清除筛选
gov.sg

@Govsg · Post #2964 · 17.03.2025 г., 08:02

#COS2025 – We will continue to support the healthcare sector by increasing our healthcare facilities islandwide and strengthening the healthcare workforce. Read more ⬆️ Infographic: Ministry of Health

Hashtags

gov.sg

@Govsg · Post #2949 · 16.03.2025 г., 08:04

#COS2025 – The Government will continue to support the health and well-being of people across all ages. Some of our plans include: ✅Grow Well SG, a programme with scheduled health checks and screenings for students ✅Continued support of active ageing initiatives and senior volunteerism ✅Improving accessibility to mental health services Find out more above ⬆️ Infographic: Ministry of Health

Hashtags

gov.sg

@Govsg · Post #2930 · 13.03.2025 г., 03:15

#COS2025 – The Government is committed to nurturing a culture of giving and co-creation. We will do this through: ✅ Added funding for our social services ✅ Supporting community-centric, ground-up initiatives ✅ A 10-year Transformation Roadmap for co-ops ✅ Increasing engagements with our youth in building a shared future Infographic: Ministry of Culture, Community and Youth

Hashtags

gov.sg

@Govsg · Post #2922 · 13.03.2025 г., 03:00

#COS2025 – We will provide various platforms to support the sporting and artistic aspirations of the people through: 1️⃣ Increasing support for Arts education across all ages, with new scholarships and programmes 2️⃣ The Sports Facilities Master Plan to make sports facilities affordable for the public 3️⃣ Improving support for persons with disabilities with 5 Para Sports Community Hubs and a Sports Fund 4️⃣ A Frailty Prevention Programme to promote healthy lifestyles for seniors 5️⃣ Improving the support system for our local athletes Infographic: Ministry of Culture, Community and Youth

Hashtags

gov.sg

@Govsg · Post #2917 · 12.03.2025 г., 09:32

#COS2025 – The arts and heritage play a vital role in strengthening our national identity. The Government will continue to support this sector by: ✅Encouraging Singaporeans to attend local arts and heritage programmes ✅Promoting participation in arts programmes to enliven our public spaces ✅Safeguarding our heritage through Heritage Activation Nodes and supporting our heritage businesses Infographic: Ministry of Culture, Community and Youth

Hashtags

gov.sg

@Govsg · Post #2912 · 12.03.2025 г., 09:15

#COS2025 – The Government will continue to strengthen social cohesion and bring people together to create an inclusive community for the future. Find out more about our initiatives and plans. ⬆️ Infographic: Ministry of Culture, Community and Youth

Hashtags

gov.sg

@Govsg · Post #2905 · 11.03.2025 г., 11:35

#COS2025 – Find out how the Government is building a thriving digital future for all ⬆️ Infographic: Ministry of Digital Development and Information

Hashtags

gov.sg

@Govsg · Post #2900 · 11.03.2025 г., 06:00

#COS2025 – Building a brighter and better Singapore for all families calls for whole-of-society support. This includes: ➡️ Providing enhanced assistance and resources to parents ➡️ Empowering vulnerable groups, including persons with disabilities and their families ➡️ Strengthening partnerships across sectors for a strong social service ecosystem Infographic: Ministry of Social and Family Development

Hashtags

gov.sg

@Govsg · Post #2892 · 11.03.2025 г., 02:33

#COS2025 – We will keep healthcare affordable and sustainable for all by: ✅ Improving healthcare affordability for outpatient treatments ✅ Strengthening support for oral health ✅ Improving support and affordability of long-term care ✅ Having better support for fertility preservation ✅ Having more drugs eligible for enhanced subsidies Find out more ⬆ Infographic: Ministry of Health

Hashtags

gov.sg

@Govsg · Post #2877 · 10.03.2025 г., 11:03

#COS2025 – The Government is committed to supporting Singaporeans and businesses to become future-ready. We will continue to: 1⃣ Empower Singaporeans to build resilient careers through Career Health SG 2⃣ Transform businesses with a new Enterprise Workforce Transformation Package to adapt and grow 3⃣ Foster inclusive and safe workplaces through the review of the Employment Act Infographic: Ministry of Manpower

Hashtags

gov.sg

@Govsg · Post #2869 · 07.03.2025 г., 10:17

#COS2025 – Here’re the key initiatives and updates to drive Singapore’s green transition forward. Find out more here. Infographic: Ministry of Sustainability and the Environment

Hashtags

gov.sg

@Govsg · Post #2859 · 06.03.2025 г., 10:52

#COS2025 – We will maximise the potential of education by: ✅Nurturing students holistically and fulfilling their potential ✅Supporting students with special educational needs ✅ Supporting lifelong learning Find out more here. Infographic: Ministry of Education

Hashtags

12
ПретходнаСтраница 1 од 2Следна