Один из самых удобных способов записать данные это использование готовых форматов, такие как JSON или YAML.
Из плюсов такого подхода стоит отметить вот что:
🔸 готовый, повсеместно используемый и поддерживаемый формат
🔸 простой и понятный файл, удобочитаемый для человека
🔸 можно легко редактировать в любом текстовом редакторе без специальных программ и библиотек
Но есть и минусы
🔹 затраты времени при записи файла (кодирование данных в нужный формат строки)
🔹 затраты времени при чтении файла (декодирование данных в Python объекты)
🔹 размер файла увеличивается из-за разметки данных (скобки, запятые, переносы, отступы...)
🔹 перед записью все данные должны быть помещены в память в полном объёме (не всегда)
🔹 при чтении необходимо считать весь файл в память и только потом декодировать данные
Если нужно писать немного данных в несколько файлов, то затраты по времени не ощутимы. Обычно это файлы конфига или какие-либо метаданные. Это отличный вариант под такие задачи.
Есть и другой поход к записи файлов - это бинарные файлы. Используется, когда данных достаточно много и никто их не собирается читать глазками😳.
🔸 очень быстрая запись
🔸 чтение значительно быстрей чем JSON, YAML итд
🔸 размер файла значительно меньше, так как нет разметки
🔸 можно записывать данные по мере поступления не загружая всё в память
🔸 можно извлечь любую часть данных независимо
Из минусов
🔹 нужно определить свой формат записи данных (если не используете готовую спецификацию определённого формата)
🔹 не получится открыть файл и визуально понять что там записано, а для чтения файла потребуется знать его спецификацию.
🔹 не так-то просто создать такой файл без специальной библиотеки
В таком виде удобно записывать большой массив любых однородных данных. Например, мониторинг валютной биржи или кэшированная анимация 3D геометрии.
(Это не означает что нельзя записать данные разного типа, просто это будет не так удобно)
Представьте себе JPG-картинку. По сути это немного мета-информации и большой массив пикселей. Тоже самое со звуком или видео файлом. Поэтому, если вы попробуете открыть картинку в текстовом редакторе вы увидите что-то вроде такого
f15d cd29 a564 4578 ...
09e2 9bc4 a696 1253 ...
84e9 4de1 3b23 c24a ...
2534 5161 28e0 709d ...
...
Это и есть записанные байтики. И для их чтения требуется определённый софт который знает что с ними делать. Под каждый тип файла.
К чему это я? Читайте в следующем посте...
#tricks#basic
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
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
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
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
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
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
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
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
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
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
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
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