Один из самых удобных способов записать данные это использование готовых форматов, такие как 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
#英文#港聞
Oct 4: Yung Wai-yip was subdued for holding white flowers. People nearby question the necessity of the force used by the #HKPolice.
Credit: boomheadhk
🍎保留一點真相、一些堅持:
https://t.me/appledailyhk26
🍎蘋果報料熱線: @Appledailyhk_bot
🍎蘋民不蘋則鳴!2.0
https://t.me/hkerappledaily2
#英文#港聞
More info about #721YuenLongTerrorAttack from the book "Among the Braves". It says that there were 5 different triad groups involved in the attack. They had a WhatsApp group which the #HKPolice had access to.
"A week prior, members of five separate triad groups joined a WhatsApp group to discuss plans to “defend their homeland,” Yuen Long. It was rare for these groups to come together, as they often clashed over their share of illicit business. As the triad groups coordinated their plans for July 21, a detective sergeant from the anti-triad bureau that oversaw the area was reading along. He had managed to gain access to the group chat, giving him unfettered insight into the plans."
The article also reported that Stephen Ng, political assistance to the mainland affairs mentioned about "wear white only" dress code.
"The political assistant to the secretary for mainland affairs had invited some others to join him at the banquet. He gave them a very specific dress code: Wear only white.”
5 years ago today, Chan Yin Lam passed away mysteriously. During 2019, many HongKongers went missing or died. Several times #HKPolice were caught throwing bags with the size of a human into the sea.
Her body was found in the sea, naked, yet people knew her claimed that she was a diver.
#HKProtest#neverforgiveneverforget
#FreeHK
#英文#港聞 #721
After 4 years, more information about #721YuenLongTerrorAttack has been revealed as the trial against Lam Cheuk-ting, a former democratic lawmaker who claimed to be there to understand the situation.
Witness B, who was a staff at the station time, said that police contacted the station through whatsapp to send 2 police to monitor the station on July 19th, 2 days before the attack.
On 20th, police arranged to have 2 police to standby at the monitor room starting at 5:00PM on 21st.
There were 2 police in the monitor room during the attack on 21st.
Clearly, #HKPolice knew that the local thugs had planned the attack 2 days before the incident.
🍎保留一點真相、一些堅持:
https://t.me/appledailyhk26
🍎蘋果報料熱線: @Appledailyhk_bot
🍎蘋民不蘋則鳴!2.0
https://t.me/hkerappledaily2
#HongKongers express fear as govt considers expanding #HKPolice power under proposed #Article23 security law. Extended detention period without charge and restrictions on legal representation raise concerns about #individualrights and freedoms.
https://hongkongfp.com/2024/03/07/hong-kong-considers-extending-detention-period-of-arrestees-to-up-to-14-days-in-national-security-cases/
#HongKong#PolicePower
#英文#港聞
Oct 17: A student held piece of paper writing "721唔見人" at a college recruitment event which #HKPolice participated. It refers to the day no police showed up when thugs attacked citizens indiscriminately on July 21, 2019. The school security told him to leave soon after.
#721YuenLongTerrorAttack
#721YuenLongAttack
#HKPoliceTerrorist
🍎保留一點真相、一些堅持:
https://t.me/appledailyhk26
🍎蘋果報料熱線: @Appledailyhk_bot
🍎蘋民不蘋則鳴!2.0
https://t.me/hkerappledaily2
Jun 15: Leung Ling-kit wore a yellow raincoat with an umbrella standing at Pacific Place Patio at 4:30. He wrote “Carrie Lam kills Hong Kong” & “Black Cops are cold blooded” on a banner and hang it at the building for everyone to see. Police and negotiators went but did not allow anyone to go near him. At 9:15pm, he jumped down. That was the beginning of the 2 million+1 people march the next day.
People still commemorate him in Hong Kong to this day while countless of #HKPolice was standing by as if having a flower in hand can damage #nationalsecurity. This is the excuse they use to arrest people anyway. The laws that we having been fighting against, the extradition bill, national security law & article 23 are laws that criminalize thoughts.
#leunglingkit#HongKongProtest#5demandnot1less#fightforfreedom#standwithhongkong