Один из самых удобных способов записать данные это использование готовых форматов, такие как 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
🌍 Machu Picchu in Peru was built atop a mountain ridge by the Incas around 1450. Its stone walls fit together so precisely that some areas withstand earthquakes without mortar. ✨
#heritage⚡#archaeology⚡#mountains⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Machu Picchu in Peru is a heritage site set amid mountain peaks and cloud forests. Its stone terraces and temples blend ancient Inca engineering with dramatic natural scenery. ✨
#heritage⚡#archaeology⚡#landscape⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
A gold coin found in 1713 in Transylvania is likely genuine. The coin shows a Roman ruler named Sponsian, who was long believed to be fictional. Tests found real ancient wear and soil deposits, suggesting he was a real leader during the 3rd-century Roman crisis.
🪙🏛️
[Read more]
@googlefactss
#history#ancientrome#archaeology#facts
🌍 The ancient city of Angkor in Cambodia covered more land than any other pre-industrial city, with a vast network of canals and reservoirs that shaped both its culture and the landscape for centuries. ✨
#historicalgeography⚡#archaeology⚡#settlement⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The lost city of Cahokia once stood near present-day St. Louis, with earthen mounds and a population rivaling European cities around 1100 CE—making it North America’s largest urban center before Columbus. ✨
#historicalgeography⚡#archaeology⚡#civilization⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌎 In the Nevada desert, the 2,000-year-old Lovelock Cave yielded mysterious oversized sandals, giant bones, and duck decoys. While duck decoys are confirmed as Native American artifacts, reports of giant bones and massive sandals remain unverified, fueling legends of a lost tribe. Archaeologists still debate the origins and meaning of these unusual finds. ✨
#history⚡#archaeology⚡#mystery
👉subscribe Interesting Planet
👉more Channels
🌎 The disappearance of the 1,200-year-old Maya city of El Mirador remains an unsolved mystery. Once a major metropolis with vast pyramids in Guatemala, it was suddenly abandoned around 150 CE. Archaeologists have not found evidence of war, plague, or fire to explain why its tens of thousands of residents left so abruptly. ✨
#history⚡#archaeology⚡#mystery
👉subscribe Interesting Planet
👉more Channels
🌎 The disappearance of the Ninth Roman Legion, Legio IX Hispana, remains one of history’s greatest unsolved mysteries. Records show the legion vanished from Roman chronicles after around 120 CE in Britain. Despite searches, no definitive evidence of its fate or mass grave has ever been found. ✨
#history⚡#mystery⚡#archaeology
👉subscribe Interesting Planet
👉more Channels
🌎 The mysterious ancient city of Great Zimbabwe was built using massive stone walls without mortar, yet no written records explain how its builders achieved such precise engineering. Archaeologists estimate the complex appeared between the 11th and 15th centuries and covers over 7 square kilometers. ✨
#history⚡#archaeology⚡#mystery
👉subscribe Interesting Planet
👉more Channels
🌎 In 2014, archaeologists uncovered a set of 2,000-year-old Roman lead tablets in a well in Britain. These inscribed tablets feature curses, prayers, and personal wishes, puzzling researchers with unusual languages and names not seen in surviving Roman texts. Over 130 of these "curse tablets" were recovered from the site in Bath. ✨
#archaeology⚡#mystery⚡#history
👉subscribe Interesting Planet
👉more Channels
🌎 The lost city of Ubar, often called the "Atlantis of the Sands," is a legendary ancient settlement thought to be buried under Oman’s deserts. Satellite imagery and excavations in the 1990s revealed buried structures at Shisr, but no proof has confirmed Ubar’s identity or vast wealth described in Arabian lore. ✨
#history⚡#mystery⚡#archaeology
👉subscribe Interesting Planet
👉more Channels
🌎 The disappearance of the English colony at Roanoke Island in the late 16th century remains unsolved. When resupply ships arrived in 1590, the settlers were gone, with "CROATOAN" carved into a post as the only clue. Archaeologists have found no definitive evidence, and the fate of over 100 people is still a mystery. ✨
#history⚡#archaeology⚡#mystery
👉subscribe Interesting Planet
👉more Channels