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

Резултати

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

Пребарај: #factfriday

当前筛选 #factfriday清除筛选

What you eat matters more than you think. ✅Good nutrition fuels your body, strengthens your immune system, and helps you resist infections like flu, cholera, and other communicable diseases. Healthy choices today, stronger immunity tomorrow.💪 #FactFriday#HealthyLiving#NCDCNigeria

#FactFriday Contaminated water can spread illnesses which affects millions of people every year. Clean water and proper hygiene practices can greatly reduce health risks and improve wellbeing. Protect yourself and your loved ones by: ✔️ Drinking only safe and clean water ✔️ Practicing good hand hygiene: Wash hands with soap under clean running water ✔️ Keeping your environment clean and free from waste ✔️ Following public health guidelines on sanitation ✨Your small daily actions can prevent big health problems. Drink Clean, Stay Safe, Stay Healthy! #FactFriday#HealthyLiving#NCDCNigeria

#FactFriday: _Powering your mind, even at rest! ✨_ 🧠 Did you know your brain uses about 20% of your body’s energy even when you’re resting? This energy keeps your brain cells active, helps process information, regulates your body systems, and keeps you alert. 💡 Take care of your brain with: 🍎 Proper nutrition 😴 Enough sleep 🧘 Regular self-care Stay healthy, stay sharp! #FactFriday#HealthyLiving#NCDCNigeria

#FactFriday Clean hands is one of the simplest and most effective ways to stay healthy and protect those around you from diseases👌 Washing your hands with soap under clean running water for just 20 seconds can reduce your risk of infection by up to 50%? 🙌🏽 Make handwashing a daily habit ✅️ #FactFriday#HandHygiene#HealthyLiving#NCDCNigeria

#FactFriday Every year, mosquitoes are responsible for over 700,000 deaths by spreading diseases like malaria, dengue, and yellow fever. 💡 Protect yourself: ✅ Sleep under insecticide-treated nets ✅ Eliminate stagnant water around your home ✅ Use mosquito repellents Small insect, Big threat. Take action today!📌 #FactFriday#MosquitoFacts#NCDCNigeria

#FactFriday Feeling better doesn’t mean the infection is gone. Stopping antibiotics without proper guidance can fuel Antimicrobial Resistance (AMR) making infections harder to treat. ✔️Always follow your healthcare provider’s advice. ✔️ Only use antibiotics when prescribed ✔️ Always complete your dose ✔️ Take antibiotics exactly as prescribed ✔️ Don’t stop, skip, or share medications. ✅Your actions today protect your health tomorrow.! #FactFriday#StopAMR#PublicHealth#NCDCNigeria

#FactFriday: Good Food, Good You! 🥬🥦Adding more fruits and vegetables to your meals can be a game changer for your health. They are filled with Vitamins, Minerals and fiber that helps boost your immunity, Protect your heart and lower the risk of chronic diseases. Healthy eating starts with fruits and Vegetables✅️ #FactFriday#HealthyLiving#HealthyHabits#NCDCNigeria.

#FactFriday 💡 Did you know? Not all bacteria are harmful. In fact, many are beneficial — helping your body digest food, absorb nutrients, and maintain a healthy immune system. Understanding the role of good bacteria is key to making informed decisions about hygiene, antibiotics, and overall health. #FactFriday#NCDCNigeria#TakeResponsibility#PublicHealthFacts

#FactFriday 💡With proper hygiene, safe practices, and protective measures, dangerous communicable diseases like Ebola can be prevented or controlled? 👐 Staying informed and taking responsibility keeps you and your community safe. ✔️ Practice good hygiene ✔️ Follow health guidelines ✔️ Stay alert and protect others #TakeResponsibility#StaySafe#NCDCGov

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