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

Резултати

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

Пребарај: #vainterview

当前筛选 #vainterview清除筛选
Venezuelanalysis

@venanalysis · Post #1813 · 22.11.2024 г., 21:43

Cooperation Jackson is a coop-based organization working for Black self-determination and economic democracy in Jackson, Mississippi. Activist and writer Kali Akuno is one of the project’s founders. In the latest VA interview, Akuno discusses his long-standing relationship with the Bolivarian Revolution and his efforts to build connections between the revolutionary process in Venezuela and the work that is being done in Mississippi. Read the full interview here 👉🏼https://shorturl.at/nwm4z #internationalsolidarity#sanctions#VAInterview

Venezuelanalysis

@venanalysis · Post #1860 · 24.01.2025 г., 19:04

Along the Orinoco River, fishing has long been a way of life rooted in collective work and respect for nature. Under the US blockade, fisher folk in the Ayacucho Commune are addressing challenges with ingenuity and solidarity. From boat rotations to crafting curiaras together, they are building resilience and self-governance while working toward food sovereignty. As José Flores, the state coordinator of fisher folk for the Ayacucho Commune, says, "the river brings us together." 🔗 Read the full report here 👉🏽https://shorturl.at/4OGYk #VAInterview#CommunalandWorkingClassResistance#Communes

Venezuelanalysis

@venanalysis · Post #1855 · 17.01.2025 г., 17:46

In Puerto Ayacucho, Ayacucho Commune fisherfolk combines tradition with communal organization to counter the effects of US sanctions. To secure food sovereignty, they plan to build a refrigeration facility to bypass exploitative intermediaries. As José Flores, state coordinator of fisher people for the Ayacucho Commune, said: 'Fishing is more than work; it binds the community together.' Learn more in VA’s latest Communal Resistance series interview: https://venezuelanalysis.com/interviews/the-ayacucho-commune-a-fishing-community-on-the-orinoco-part-i/ #VAInterview#CommunalandWorkingClassResistance#Communes

Venezuelanalysis

@venanalysis · Post #1737 · 06.09.2024 г., 23:10

Located near Miraflores Palace in Caracas, La Minka Collective operates from a dynamic multi-use cultural space. The building, a former printing press, is adorned with a mural representing Venezuela’s popular history and now hosts classrooms, a radio studio, and a community kitchen, each dedicated to advancing grassroots democracy. In the latest VA interview, Natalia Molina, a founder of the organization, reflects on La Minka’s origins, its cultural projects, and the collective’s work in building a socialist commune while defending the Bolivarian Process after the post-July 28th fascist attacks. Read the full interview here: https://shorturl.at/qoEqK #Communes#Culture#VAInterview

Venezuelanalysis

@venanalysis · Post #1766 · 04.10.2024 г., 17:20

In the latest VA interview, Javier Couso, a keynote speaker at the recent World Congress Against Fascism in Caracas discussed the fascist attacks on Venezuela. He highlighted Venezuela’s resistance to fascist tactics by liberal democracies, marking it as a key player in the global struggle for sovereignty and democracy. 'Venezuela is a beacon in the fight for sovereignty and true democracy,' stated Couso. Read the full interview here 👉🏼https://shorturl.at/Ej6UL #VAInterview#Fascism#PresidentialElections2024

Venezuelanalysis

@venanalysis · Post #1940 · 18.04.2025 г., 19:48

📝 INTERVIEW | Venezuela’s 2025 Elections, Electoral Safeguards and Constitutional Reform: A Conversation with Oliver Rivas In the latest VA interview, Deputy Oliver Rivas breaks down the 2025 candidate selection process, rooted in grassroots assemblies and internal evaluations, and explains how the Simón Bolívar Law protects Venezuela’s democracy from foreign interference. He also looks ahead to the upcoming constitutional reform, which aims to enshrine the commune in the nation’s charter. 🗣 “The process opens a national debate on the type of state we want.” 📖 Read the full interview here: https://venezuelanalysis.com/interviews/venezuelas-2025-elections-electoral-safeguards-and-constitutional-reform-a-conversation-with-oliver-rivas/ #2025ConstitutionalReform#LegislativeRegionalElections2025#VAinterview

Venezuelanalysis

@venanalysis · Post #1786 · 25.10.2024 г., 19:00

Amazonian Huo̧ttö̧ja̧ People and the Bolivarian Process The Río Cataniapo Commune showcases the strength of Indigenous organizations in the Venezuelan Amazon, with approximately 1,500 participants committed to communal living and traditional agriculture. 'Our way of living is far more communitarian than the sabari way of life,' notes Irene Pérez, of the 5 de Julio-Las Pavas Communal Council, is an artisan and campesina, emphasizing their commitment to ensuring no one goes hungry. Read the full interview here: https://venezuelanalysis.com/general/amazonian-huo%cc%a7tto%cc%a7ja%cc%a7-people-and-the-bolivarian-process-rio-cataniapo-commune-part-ii/ #VAInterview#communalresistanceseries#communes#indigenouspeoples

Venezuelanalysis

@venanalysis · Post #1838 · 20.12.2024 г., 23:46

Cuban theologian Joel Suárez reflects on Hugo Chávez’s integration of spirituality into his leadership, noting his embodiment of a grassroots liberation theology that combined political vision with cultural expressions like baseball and music. Read the full interview here 👉🏽https://venezuelanalysis.com/interviews/chavez-spirituality-and-celebration-a-conversation-with-joel-suarez-part-ii/ #Chavez#religion#VAInterview

Venezuelanalysis

@venanalysis · Post #1802 · 08.11.2024 г., 21:22

In the Río Cataniapo Commune, communal power and tradition intersect to sustain food sovereignty and resist the impacts of the US blockade. The commune produces its staple casabe from yuca, managing every step from harvest to market. Read the full interview here 👉🏼https://shorturl.at/WRgF9 #VAInterview#communalresistanceseries#communes#indigenouspeoples#communalandworkingclassresistance

Venezuelanalysis

@venanalysis · Post #1779 · 18.10.2024 г., 21:44

‘The Commune Is Nothing New Here’: The Rio Cataniapo Commune The Rio Cataniapo Commune, located in the Venezuelan Amazon, brings together 1,500 people, mainly Indigenous, to protect the Cataniapo River and develop a sustainable agricultural economy. As Enrique Martínez, a Huo̧ttö̧ja̧ leader, explains: ‘Self-government and collective ownership are part of our heritage.’ Indigenous leadership remains key, but the community also seeks modern improvements while preserving tradition. Read the full interview here 👉🏼https://shorturl.at/Xgst1 #VAInterview#communalresistanceseries#communes#indigenouspeoples#communalandworkingclassresistance

Venezuelanalysis

@venanalysis · Post #1749 · 20.09.2024 г., 21:13

Ximena González Broquen, a social scientist leading a center at Venezuela’s prestigious Institute for Scientific Research (IVIC) and compiler of several essay collections, discusses the Ethics of Liberation as a framework that challenges the top-down, market-driven logic of conventional scientific research institutes in the latest VA interview. She advocates for a more democratic research environment while aiming to build bridges with organized communities. Read the full interview here 👉🏼https://shorturl.at/PHqTf #VAInterview#Revolution#science#interview

Venezuelanalysis

@venanalysis · Post #1556 · 10.05.2024 г., 21:03

On Fascism and Other Maladies: A Conversation with Luis Britto García One of Venezuela’s most respected intellectuals talks about fascism and corruption scandals in the lead-up to the presidential elections. Read the full interview here 👉🏼shorturl.at/cexUZ #VAInterview#LuisBrittoGarcia#Venezuela#presidentialelections2024#interview#corruption#fascism