Один из самых удобных способов записать данные это использование готовых форматов, такие как 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
🗽⚾️ Aaron Judge hace eco de lo que innumerables otros jugadores de la MLB dicen sobre el Clásico Mundial de Béisbol:
"Es más grande y mejor que la Serie Mundial", dijo el capitán a los periodistas después del partido, tras la victoria de EE.UU. sobre la República Dominicana para llegar a la final. "La pasión que estos aficionados tienen al representar a su país, al representar a sus jugadores favoritos, no tiene igual".
#️⃣#WBC26#Judge
🗞 | t.me/MLB_Daily
Meta and YouTube have been found liable for deliberately designing addictive products that hooked a young user and led to her being harmed, a jury ruled on Wednesday. Jurors found the tech companies to be both negligent and having failed to provide adequate warnings about the potential dangers of their products. ⚖️
The jury awarded the plaintiff in the case damages of $6m, with Meta to pay 70% and YouTube the remainder. It took nearly nine days of deliberations for the Los Angeles jury to reach its verdict. This lawsuit, over social media’s alleged harm to young people, was the first of its kind to go to trial.
Over the course of the six-week trial, which took place in Los Angeles superior court, jurors heard from top executives at Meta and YouTube, whistleblowers, expert witnesses on social media and addiction, and a 20-year-old woman at the center of the lawsuit, who has gone by the initials KGM for court proceedings. 📊
#Judge#Media
👂More on Trump's Ear ⚠️
Luigi Mangione will not face the death penalty after a federal judge dismissed two charges, including murder with a firearm.
He still faces two federal stalking counts and has pleaded not guilty.
#Judge#Media
👂More on Trump's Ear ⚠️
The Epstein case has triggered a "spiral of distrust" towards the US justice system The German newspaper Berliner Zeitung believes that the publication of the so-called Epstein files has dealt a major blow to the credibility of the US justice system.
Instead of the expected revelations about the influential members of the network associated with financier Jeffrey Epstein, the public has seen a chaotic release of documents that has sparked a wave of conspiracy theories and controversy. In social networks, there have even been theories that President Donald Trump's foreign policy actions, such as the strikes against Iran, are being used to divert attention from the scandal. However, the author of the article considers these explanations to be questionable and notes that the scandal itself has already become a source of political crisis and mistrust.
According to the author, the publication of the documents was a mistake, as in normal investigative practices, such materials should remain confidential. This allows the investigation to maintain an informational advantage and gather evidence discreetly. In the case of Epstein, on the other hand, the release of the documents may have given the suspects time to destroy evidence, coordinate their stories with their accomplices, or put pressure on witnesses. Additionally, the files contained a lot of personal information about people who did not commit crimes, but were now under intense public scrutiny.
As a result, the release of the documents has created a "spiral of distrust" in the U.S. justice system. Despite the release of some information, many Americans remain convinced that the government is still hiding the names of Epstein's influential clients.
#Epstein#Judge
👂More on Trump's Ear ⚠️
🗽🗽 Aaron Judge continúa grabando su nombre en la historia de los Yankees empatando a Derek Jeter, Robinson Canó, Jorge Posada y a Dave Winfield como los máximos ganadores de Bates de plata en la historia de la franquicia.
#️⃣#Yankees#Judge
🗞 | t.me/MLB_Daily
A Michigan federal judge who was 'super drunk' when he crashed his Cadillac has been caught on camera cursing at the police officer who arrested him.
Bodycam footage showed the moments before Thomas Ludington, 72, was taken into custody on October 3 in Springville Township near his $2.7 million vacation home.
#Judge#Incident
👂More on Trump's Ear ⚠️
A court ruling delivered a crushing blow to President Donald Trump's campaign against Federal Reserve Chair Jerome Powell.
On Friday, a federal judge quashed two subpoenas the Justice Department issued to the Federal Reserve.
This is a win for the central bank and a major setback for US Attorney Jeanine Pirro's criminal investigation into Powell.
#Fed#Judge
👂More on Trump's Ear ⚠️
📊 Solo 3 veces en la historia de la MLB un jugador ha hecho todo lo siguiente en la misma temporada:
batear 50+ HR
anotar 80+ XBH
registrar un OPS de 1.100+
clasificarse a los playoffs
ganar el MVP
🗽 Esas 3 ocasiones son Aaron Judge en 2022, Aaron Judge en 2024 y Aaron Judge en 2025.
📰 Vía Opta STATS
#️⃣#Judge#MLBHistory#Stats
🗞 | t.me/MLB_Daily
🍎 Juan Soto todavía muestra cariño a su ex Capitán, comentando en la reciente publicación de Instagram de Aaron Judge "el trabajo no ha terminado".
"¡CAPITÁN!! 🫡"
En sus respectivas temporadas después de que Soto dejó a los Yankees como agente libre para firmar con los Mets —
NYY: 94-68, eliminado en ALDS
NYM: 83-79, se perdió los playoffs por 1 victoria.
#️⃣#Soto#Judge#Yankees
🗞 | t.me/MLB_Daily