Один из самых удобных способов записать данные это использование готовых форматов, такие как 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
💡Power outages continue in Bali
⚡️ Following a massive blackout on May 2 caused by damage to an undersea cable between Java and Bali, power outages persist on the island.
ℹ️ Yesterday, May 5, the company conducted several scheduled outages on the island. This is due to maintenance following the outage as well as measures to stabilize the power grid. Full restoration may take several days.
#accidents@BaliNews
📰FINNS Beach Club spoiled a Balinese ceremony on Berawa Beach
🎆 Bali provincial authorities have called for the responsibility of the organizers of a fireworks display during a Hindu ceremony at Berawa Beach. The fireworks at Berawa Beach were launched by the FINNS beach club.
📱 In a video that has circulated on the web, fireworks can be seen exploding repeatedly, while a Balinese priest concentrates on performing a prayer. The solemn and quiet atmosphere has changed to a noisy and hectic one.
@BaliNews
#accidents
🐘Elephant kills keeper in Bali safari park
📰 A tragedy has occurred at the Bali Safari and Marine Park in Bali. An elephant keeper was killed by one of his charges. 27-year-old Komang Resi Yasa died after sustaining multiple injuries when he was attacked by an elephant named Gadi.
😔 The aggressive elephant was put to sleep by safari staff shortly after the incident. The elephant show has been suspended.
@BaliNews
#accidents
💻Hackers broke into the Indonesian government server and demanded 8 million dollars
🪪 Indonesian authorities told about the reasons for the failure of the electronic visa portal, which did not work for several days. The disruption was caused by a hacker attack on the server of the National Data Center of the Indonesian Ministry of Information.
✔️ The digital immigration system, which is used at Indonesia's main international airports, has now been restored. Autogates, residence permit and visa databases are operating as normal.
❗️ Control of the passport system has not yet been restored.
@BaliNews
#accidents
🐍A five-metre python swallowed a woman in Indonesia
👀 This is not a plot of a new film, but the real sad story of a woman who died.
😧 In South Sulawesi, a python strangled and swallowed a 45-year-old local resident. The wildlife victim was discovered after opening up the snake.
🐍 Farida, which was the name of the deceased, had gone to sell groceries at a local market and disappeared. Her husband went in search of her and found her bag and other belongings in the jungle. The woman was reported missing and a search for her began. With the help of locals, a five-metre python with a badly bloated belly was found in the forest after some time.
"The suspicion arose that he and swallowed the victim. Indeed, after the snake was opened, the body of the missing person was found inside its stomach,’
said Kalempang village chief Suardi Rosi.
🌴 Statistics show that you should not seriously fear that you will suddenly be attacked by a python in Bali. However, if you are a traveller who often travels to remote parts of Indonesia and goes deep into the jungle, be very careful.
@BaliNews
#accidents
👮🏻♂️A tourist was deported from Bali over vandalism
🪓Russian citizen deported from Bali after vandalizing restaurant with an axe. As head of the regional department of Indonesia's Ministry of Justice, Pramella Yuniar Pasaribu reported that the man had attacked Capri Bali restaurant being furious about unrequited love with a local woman.
The Russian was deported with a ticket his friend helped him buy. The deportee will be blacklisted by Indonesia's Directorate General of Immigration.
🗯️ Pramella Yuniar Pasaribu.
@BaliNews
#accidents
📰 Autopilot failed to handle the situation
👨⚖️ A Tesla Cybertruck owner has filed a lawsuit against Tesla, seeking $1 million in damages after a crash she claims was caused by the FSD autopilot system.
😁 The lawsuit also accuses the company of “negligent hiring and retention” of Elon Musk as CEO.
🤐 Tesla representatives have not commented on the lawsuit so far. Meanwhile, the National Highway Traffic Safety Administration (NHTSA) continues to review hundreds of incidents in which the FSD system may have been involved.
#Tesla#accidents@Car_News
😁When Elon Musk’s brainchild got rude
📰 A Tesla scratched its owner’s other car while he was trying to drive away.
🥴 The Model X detected its owner approaching and decided it needed to open the door.
😐 As a result, both the Tesla and the Mini Cooper ended up with scratches.
#Tesla#accidents@Car_News
🪨Another cliff collapse in Uluwatu
❗️ Tourists are asked to be careful.
📰 Social networks are actively discussing fresh footage showing a serious cliff collapse in Uluwatu district. The cliff collapsed near the Tanjung Mebulu Lighthouse. Tourists love to go there because of the incredible views from the high cliff.
🚧 But now this ledge does not look so attractive - visitors are asked not to go closer than three meters to the edge. Moreover, it is likely to be closed.
@BaliNews
#accidents#places
🚢Ferry sinks off Bali: dozens missing
📰 The tragedy occurred on the evening of July 2 off the coast of Bali: the KMP Tunu Pratama Jaya ferry, traveling from the port of Ketapang in eastern Java to the port of Gilimanuk in Bali, sank about half an hour after departure. There were 53 passengers and 12 crew members on board, as well as 22 vehicles, including 14 trucks.
😔 According to official data, rescuers managed to find the bodies of at least four victims and save 23 people — many of whom were found unconscious after several hours of drifting in rough waters. The fate of 38 people remains unknown.
🆘 The search and rescue operation is ongoing, involving nine vessels, including tugboats and inflatable boats.
#transport#accidents@BaliNews
📱Indonesian authorities are preparing to block Telegram
📰 The country's Minister of Communications and Information Budi Aryeh Setiadi said that Telegram is one step away from being blocked on the territory of Indonesia. All because of its refusal to co-operate with law enforcement.
We have warned Telegram twice, because on this platform there is a mass distribution of not only gambling, but also pornography.
said Budi Aryeh Setiadi at the Jakarta Communications and Information Office.
🤞 However, the communications and information minister did not give an exact timeline for when Durov's messenger will be out of Indonesian laws. At the moment it is known about two letters that the Indonesian authorities sent to the Telegram office. In addition, an investigation is ongoing. And it is on its results, apparently, that the verdict that will be handed down to the messenger will depend.
@BaliNews
#accidents#laws
🕵🏼Mass capture of cybercrime suspects occurred in Bali
👮♂️ Indonesian authorities detained more than a hundred foreign nationals. This massive operation was carried out by the Bali Becik unit, which is the name of a special branch of immigration enforcers in charge of controlling foreigners who break the law. Part of the immigration team conducted surveillance at a villa in Marga neighborhood, Tabanan regency.
💻 The detainees had no official documents and they all had expired visas. In addition, numerous computers and cell phones were found at the scene, indicating likely cybercriminal activity.
@BaliNews
#accidents#laws