Один из самых удобных способов записать данные это использование готовых форматов, такие как 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
When paying respects this Qing Ming, let’s continue to be socially responsible and observe #SafeDistancing measures. As crowds are expected at Choa Chu Kang Cemetery and government-managed columbaria, visitors are advised to send 2 representatives per household (with not more than 8 pax per group). The opening hours will be extended to 24-hours, with effect from 20 Mar until 18 Apr 2021.
Visitors driving to Mandai Columbarium during peak days will also be required to book an appointment. Visit www.nea.gov.sg/qingming2021 for more information.
From 12 Sep 2020, weekend visitors to the 4 popular markets (Geylang Serai Market, Chong Pang Market, Block 20/21 Marsiling Lane, and Block 505 Jurong West Street 52) will not be subject to the odd/even date entry restriction. However, the caps on the number of patrons allowed in the market at any one time will still be in place, to ensure sufficient #SafeDistancing. More information available at https://go.gov.sg/nea-lifting-entry-restriction-markets-12sep
During Phase 2, you may leave your home to smoke, but do so in an area where smoking is not prohibited, and observe #SafeDistancing requirements. To protect yourself and others around you, do put your mask back on as soon as you have finished smoking. From 19 Jun, Designated Smoking Areas along the Orchard Road No Smoking Zone can re-open with safe distancing measures. Smoking corners beyond the Orchard Road No Smoking Zone, can also re-open with the necessary safe distancing measures in place. www.nea.gov.sg/post-circuit-breaker-measures
From 22 Apr 2020, access to 4 popular markets will be restricted based on the last digit of patrons’ NRIC or FIN numbers, to ensure effective #SafeDistancing and safeguard public health. Patrons with NRIC/FIN ending with:
- an even last digit (0, 2, 4, 6, 8) can only visit on the even dates of the month
- an odd last digit (1, 3, 5, 7, 9) can only visit on the odd dates of the month
These 4 markets are Geylang Serai Market, Block 104/105 Yishun Ring Road (Chong Pang Market), Block 20/21 Marsiling Lane Market, and Block 505 Jurong West Street 52 Market. More information available at www.facebook.com/NEASingapore/posts/2589759427912055
If your parents or older relatives do their grocery shopping at these 4 popular markets, do share the guide (available in 4 different languages) with them! Download a copy from https://www.facebook.com/NEASingapore/posts/2590540227833975
Dine-in at #OurHawkerCentres resumes from 19 Jun! Whilst you may be excited to meet with your friends, limit the group to 5 people or less and continue to observe #SafeDistancing measures – use unmarked seats/tables, keep 1 metre apart from others, and only remove your masks when eating.
At our markets, continue to stand within the boxes marked on the floor, to maintain a safe distance. Access to the 4 popular markets will continue to be restricted based on the last digit of your identification number. More information available at www.nea.gov.sg/media/news/advisories/index/safe-management-measures-in-phase-2-at-hawker-centres-and-markets
Need your essentials? In addition to wearing a mask to buy essentials at the supermarket, schedule your grocery run on a weekday and avoid the peak periods, or opt for delivery instead. Let’s take #SafeDistancing seriously, and work together to stop the spread of COVID-19. #SGUnited
Planning dinner with your friends? Due to #SafeDistancing, there may be limited seating capacity at many places, so call in advance to make reservations first. Otherwise, opt for takeaway (bring your own containers!) or delivery 😊#SGUnited#FightCOVID19
#SafeDistancing applies everywhere – even when choosing fish and vegetables at the markets! If you have elderly neighbours or family members, help them with their marketing instead so that they can #StayHome and stay safe. #SGUnited
Only sit on seats without markings when dining in at #OurHawkerCentres to maintain #SafeDistancing. If the seating capacity is limited, #BringYourOwn clean containers and choose to take-out instead. Let’s unite to #FightCOVID19 together! 💪#SGUnited
Let’s remember to stay at least a metre apart from each other. We wouldn’t want all the effort and resources of the past few months to go to waste. Dining in at #OurHawkerCentres? Let’s not forget to #ReturnOurTrays and #BinOurTissues after enjoying the meal! #SGUnited#SafeDistancing#FightCOVID19