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

Резултати

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

Пребарај: #sciencefacts

当前筛选 #sciencefacts清除筛选
Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40970 · 24.04.2026 г., 14:03

A study on men found that eating garlic made their body odor smell more pleasant, more attractive, and less intense. Researchers collected sweat samples and had others rate the smell. Note: The study tested sweat, not their breath.🤪 🧄👃🧪 [Read more] @googlefactss #ScienceFacts#DidYouKnow#HumanBody#Research If you have ideas or feedback contact us: @Googlefactss_Feedback_bot

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40949 · 18.04.2026 г., 06:00

The human digestive system is about 7–9 meters (23–30 feet) long. The small intestine measures about 3–7 meters (10–23 feet), and the large intestine is about 1.5 meters (5 feet) long. Food typically takes 24 to 72 hours to travel from the mouth to the toilet. This time can differ depending on what you eat, how much water you drink, and how active you are. 🧠📏⏱️ [Read more 1] [Read more 2] @googlefactss #HumanBody#DigestiveSystem#ScienceFacts#DidYouKnow

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40950 · 18.04.2026 г., 14:01

A brain freeze happens when something very cold touches the roof of the mouth or the back of the throat. This causes blood vessels in that area to quickly narrow and then widen again. This change activates a nerve that sends pain signals to the brain, which is why the pain is felt in the head. The sensation usually lasts only a few seconds to about a minute. 🧊🧠⚡ [Read more] @googlefactss #BrainFreeze#HumanBody#ScienceFacts#Health If you have ideas or feedback contact us: @Googlefactss_Feedback_bot

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40291 · 10.12.2025 г., 15:03

Babies are born with around 30,000 taste buds. Adults have about one-third of that number. This means babies can taste more flavors than grown-ups. As people get older, they lose many taste buds, which changes how they experience food. 👶🍎 [Source] @googlefactss#TasteBuds#Babies#ScienceFacts

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40338 · 16.12.2025 г., 07:02

Psychopaths, often called ‘evil,’ lack empathy and guilt. They were once seen as untreatable. New studies show therapy like CBT and computer training can reduce violence and help them feel empathy. Treatment is limited but promising. 🧠💡 [Read more] @googlefactss#Psychopathy#Therapy#MentalHealth#ScienceFacts

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40179 · 24.11.2025 г., 07:03

Women outperform men in recognizing all faces, with a particular advantage for female faces. 👩‍🦰👨‍🦱 They recognize both male and female faces better than men do. Men do not show this same bias toward their own gender. [New Link1] [New Link2] @googlefactss#Psychology#FaceRecognition#GenderDifferences#ScienceFacts

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40309 · 12.12.2025 г., 23:01

Ants don't have lungs. They breathe through tiny holes along the sides of their bodies called spiracles. These connect to a network of tubes (tracheae) that deliver oxygen directly to their tissues. [Read more] @googlefactss #Ants#Biology#Entomology#ScienceFacts

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40980 · 27.04.2026 г., 05:23

People who eat the mushroom Lanmaoa asiatica raw or undercooked have reported seeing tiny human-like figures moving around them. These are called lilliputian hallucinations. Reports from people across different cultures and backgrounds describe similar details, including small figures walking on floors and furniture. The effects can begin 12–24 hours after eating and may last 1–3 days. Some cases are serious and require hospital care. Don't try this yourself.. 🍄😵‍💫🧚‍♀🦄🍄‍🟫 [Read more 1] [Read more 2] [Read more 3] @googlefactss #Mushrooms#ScienceFacts#Hallucinations#Nature#DidYouKnow If you have ideas or feedback contact us: @Googlefactss_Feedback_bot

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40329 · 15.12.2025 г., 03:01

15 December 1970, Venera-7 became the first spacecraft to land on Venus and send data back to Earth. Despite problems, it transmitted temperature information for 23 minutes after landing. The mission showed that Venus has extreme heat and pressure. [Source] @googlefactss #Venera7🚀#Venus🌍#SpaceExploration#ScienceFacts

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40563 · 20.01.2026 г., 23:01

Serge Voronoff performed experiments transplanting testicle tissue from monkeys into men and boys to try to improve health and vitality. He also grafted testicle tissue onto female goats in his research. These practices were done in the early 1900s but later found to be ineffective and controversial. 🙈✂️⚽️⚽️ [Read more] @googlefactss #SergeVoronoff#MedicalHistory#Transplants#ScienceFacts

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40666 · 17.02.2026 г., 23:01

Pregnant women have one more organ than non pregnant women. The placenta is a temporary organ that grows in the uterus during pregnancy. It connects the mother and baby through the umbilical cord. It gives the baby oxygen and nutrients and removes waste like carbon dioxide. It also makes hormones that help the pregnancy continue and lets helpful antibodies pass to protect the baby. "Fun" fact: After birth, the placenta leaves the body. Some people keep it and even consume it.. 🤰👶🍽 [Read more] [Don't eat it] #placenta#pregnancy#humanbody#sciencefacts#biology@googlefactss

Google Facts™ [ ️@googlefactss🌎]

@googlefactss · Post #40459 · 02.01.2026 г., 03:04

Isaac Asimov was born on January 2, 1920. He wrote the Three Laws of Robotics: 1. Robots can't harm humans or let them be harmed. 2. Robots must follow human orders unless it breaks the first law. 3. Robots must protect themselves unless it breaks the first or second law. 🤖📜 [Read more] @googlefactss #IsaacAsimov#Robotics#ThreeLaws#ScienceFacts

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