TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #241 · 5 мај

Можно ли в Python создавать бинарные файлы? Конечно можно. Для этого в Python есть следующие инструменты: ▫️ тип данных bytes и bytearray ▫️ открытие файла в режиме wb (write binary) или rb (read binary) ▫️ модуль struct Про модуль struct поговорим в первую очередь. Файл в формате JSON или Yaml внутри себя содержит разметку данных. Всегда можно определить где список начался а где закончился. Где записана строка а где словарь. То есть формат записи данных содержит в себе элементы разметки данных. В binary-файле данные не имеют визуальной разметки. Это просто байты, записанные один за другим. Правила записи и чтения находятся вне файла. Модуль struct как раз и помогает с организацией данных в таком файле с помощью определения форматов записи для разных частей файла. Модуль struct преобразует Python-объекты в массив байт, готовый к записи в файл и имеющий определённый вид. Для этого всегда следует указывать формат преобразования (или, как оно здесь называется - запаковки). Формат нужен для того, чтобы выделить достаточное количество байт для записи конкретного типа объекта. В последствии с помощью того же формата будет производиться чтение. При этом следует помнить что мы говорим о типах языка С а не Python. Именно формат определяет, что записано в конкретном месте файла, число, строка или что-то еще. Вот какие токены формата у нас есть. Помимо этого, первым символом можно указать порядок байтов. На разных системах одни и те же типы данных могут записываться по-разному, поэтому желательно указать конкретный способ из доступных. Если этого не сделать, то используется символ '@', то есть нативный для текущей системы. В строке формата мы пишем в каком порядке и какие типы собираемся преобразовать в байты. Запакуем в байты простое число, токен "i". >>> import struct >>> struct.pack('=i', 10) b'\n\x00\x00\x00' Теперь несколько float, при этом нужно передавать элементы не массивом а последовательностью аргументов. >>> struct.pack('=fff', 1.0, 2.5, 4.1) b'\x00\x00\x80?\x00\x00 @33\x83@' Вместо нескольких токенов можно просто указать нужное количество элементов перед одним токеном, результат будет тот же. >>> struct.pack('=3f', 1.0, 2.5, 4.1) b'\x00\x00\x80?\x00\x00 @33\x83@' Теперь запакуем разные типы >>> data = struct.pack('=fiQ', 1.0, 4, 100500) я запаковал типы float, int и unsigned long long (очень большой int, на 8 байт) b'\x00\x00\x80?\x04\x00\x00...' Распаковка происходит аналогично, но нужно указать тот же формат, который использовался при запаковке. Результат возвращается всегда в виде кортежа. >>> struct.unpack('=fiQ', data) (1.0, 4, 100500) Как видите, ничего страшного! #lib#basic

Hashtags

Резултати

Пронајдени 31 слични објави

Пребарај: #opposition

当前筛选 #opposition清除筛选
Venezuelanalysis

@venanalysis · Post #1746 · 16.09.2024 г., 21:07

Venezuelan Interior Minister Diosdado Cabello announced the arrest of a US Navy SEAL and two Spanish citizens, accusing them of plotting to assassinate President Nicolás Maduro. Authorities also seized 400 firearms and uncovered plans to attack key infrastructure. The US has denied involvement, calling the claims "categorically false." Read the full report here 👉🏼https://shorturl.at/VIMCG #Opposition#USVenezuelaRelations

Borkena

@borkena · Post #5280 · 18.11.2025 г., 05:36

Anatomy of Political Opposition in Ethiopia: Motives, Destinations, and Reasons to Reject or Accept Them. Read more. https://borkena.com/2025/11/17/anatomy-of-political-opposition-in-ethiopia-motives-destinations-and-reasons-to-reject-or-accept-them/#Ethiopia#opposition#politics

Venezuelanalysis

@venanalysis · Post #1748 · 20.09.2024 г., 14:19

Before departing for Spain, Edmundo González signed a letter acknowledging the judicial ruling that confirmed Nicolás Maduro's victory. Later, the European Parliament passed a symbolic, non-binding resolution declaring González as Venezuela's "legitimate" president. Read the full report here: https://shorturl.at/8cqhl #Opposition#presidentialelections2024

Venezuelanalysis

@venanalysis · Post #1740 · 09.09.2024 г., 18:10

Edmundo González, the US-backed opposition presidential candidate in Venezuela, has fled the country and arrived in Spain. He sought refuge in the Spanish Embassy in Caracas before being granted safe passage by Venezuelan authorities. An arrest warrant had been issued for him last week, charging him with conspiracy and other crimes. Read the full report here 👉🏼https://shorturl.at/BzsoN #PresidentialElections2024#Opposition

Venezuelanalysis

@venanalysis · Post #1736 · 04.09.2024 г., 21:05

Venezuelan authorities have issued an arrest warrant for former opposition presidential candidate Edmundo González on multiple charges, including forgery and conspiracy. The move comes after González refused to respond to summonses and amid his claim of electoral victory. Full report 👉🏼https://shorturl.at/LTiS9 #Opposition#PresidentialElections2024

Venezuelanalysis

@venanalysis · Post #1506 · 21.03.2024 г., 23:55

Venezuelan authorities have arrested two associates of opposition leader María Corina Machado, alleging a plot to incite violence similar to the 2014 and 2017 protests. The arrests aim to prevent attacks on military installations and energy companies. Full details here 👉https://bit.ly/3IPfGlA #opposition#presidentialelections2024

Venezuelanalysis

@venanalysis · Post #1485 · 26.02.2024 г., 19:05

Despite María Corina Machado's bold claim, "There will be no elections without me!" the majority of opposition factions are committed to moving forward, concentrating on offering viable alternatives for Venezuela's presidential elections. Don't miss out on the latest VA column from Clodovaldo Hernández. Click here to read more 👉🏽https://bit.ly/3OSlfD1 #Venezuela#opposition#presidentialelections2024

Venezuelanalysis

@venanalysis · Post #1884 · 19.02.2025 г., 22:26

📑🖊 ANALYSIS | Venezuela in 2025: Unexpected Turns Mark the Start of the Political Year VA columnist Clodovaldo Hernández reflects on recent events in the Trump II era and examines their impact on Venezuela’s opposition. Trump’s second term has taken an unexpected turn regarding Venezuela. His special envoy, Richard Grenell, met with Nicolás Maduro in Caracas and facilitated the return of six U.S. citizens imprisoned in Venezuela. Meanwhile, USAID funding for opposition parties, NGOs, and media has been suspended for three months, triggering internal disputes. 🔗 Read VA’s latest column here: https://shorturl.at/Ek5T1 #DonaldTrump#Opposition#USVenezuelaRelations

Venezuelanalysis

@venanalysis · Post #1825 · 04.12.2024 г., 21:42

🎙 Episode 31 of the VA Podcast is live: Is Edmundo González ‘Guaidó 2.0’? The Venezuelanalysis podcast tackles the proverbial million-dollar question everyone is talking about: is the Trump administration about to do a rerun of the “interim government,” this time with Edmundo González in place of Juan Guaidó? Host José Luis Granados Ceja is joined by fellow VA writer and editor Ricardo Vaz to talk about the different scenarios, sanctions and the economic balancing acts the Maduro government is facing. Watch the full episode: https://www.youtube.com/watch?v=Nvrvw4M2jqo #DonaldTrump#opposition#sanctions

Venezuelanalysis

@venanalysis · Post #1510 · 25.03.2024 г., 16:29

In an opinion piece by Smolarek and Alexandra, they reveal how the US-led narrative of electoral fraud in Venezuela aims to delegitimize the government. Despite scrutiny, Venezuela remains steadfast in upholding democracy amid external pressures. "After years of political instability caused by right-wing plots to overthrow the democratically elected government and even assassinate the leader, the Venezuelan government has pursued a straightforward principle." highlights the article. Read more here: https://venezuelanalysis.com/analysis/venezuelas-election-in-the-crosshairs-of-new-us-regime-change-scheme/ #NicolasMaduro#opposition#presidentialelections2024

ПретходнаСтраница 1 од 3Следна