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

Резултати

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

Пребарај: #meningitis

当前筛选 #meningitis清除筛选

Bacterial meningitis leaves 1 in 5 people with disabilities such as hearing loss, brain damage and limb loss. But meningitis is largely vaccine-preventable! Parents/caregivers are urged to visit any primary health care centre to get their children/wards vaccinated against #meningitis.

Hashtags

Your input is crucial in shaping better prevention, treatment and control strategies against #Meningitis in Nigeria. 📋Take our #Meningitis KAP Survey to share your knowledge, attitudes, and practices. 🔗Survey link https://forms.gle/R5uxSdet2nPNQvpRA

Hashtags

#Meningitis is a serious infection that can lead to severe complications & death Report immediately to a healthcare facility if you or a loved one experiences ➡️Neck pain ➡️Pain on looking at bright lights ➡️Vomiting ➡️Muscle/joint/limb pain ➡️Rash ➡️Seizures ➡️Cold hands & feet

Hashtags

Any form of #Meningitis is an emergency! ALL healthcare workers are urged to have a high index of suspicion and immediately report if they notice these signs & symptoms in their patients: ➡️Fever/severe headache ➡️Vomiting ➡️Drowsiness ➡️Rash ➡️Seizures ➡️Muscle/joint pain ➡️Stiff neck

Hashtags

The spread of #meningitis is usually through: ➡️ Direct person-to-person contact, including droplets from the nose and throat of infected persons. ➡️Close and prolonged contact with an infected individual. Visit the nearest health facility immediately if you notice any of the CSM-associated signs and symptoms.

Hashtags

#Meningitis is an inflammation of a thin layer of the connective tissue that covers the brain and the spinal cord. This inflammation can be caused by infection with bacteria, viruses, parasites, fungi, injuries and certain drugs. Know the symptoms to seek early health care. Advisory: https://ncdc.gov.ng/news/508/cerebrospinal-meningitis-public-health-advisory

Hashtags

#Meningitis is an epidemic-prone disease requiring immediate reporting in Nigeria. ALL healthcare workers are urged to have a high index of suspicion if they notice these signs & symptoms in their patients: ➡️Fever/severe headache ➡️Vomiting ➡️Drowsiness ➡️Rash ➡️Seizures ➡️Muscle/joint pain ➡️Stiff neck

Hashtags

Bacterial meningitis is largely vaccine-preventable; #meningitis vaccines are safe, effective, and give protection to your family and community. Parents and caregivers, now is the time to catch up on the childhood immunisations that protect against meningitis.

Hashtags

Hand washing is one of the most effective ways of preventing the spread of infectious diseases including #meningitis Always wash your hands with soap under running water for protection against meningitis and other deadly diseases Also ensure you and your loved ones are vaccinated with the recommended immunisations

Hashtags

Report immediately to a healthcare facility if you or a loved one experiences the below symptoms of #Meningitis ➡️Neck pain ➡️Pain on looking at bright lights ➡️Vomiting ➡️Muscle/joint/limb pain ➡️Rash ➡️Seizures ➡️Cold hands & feet Early recognition saves lives

Hashtags

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