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

Резултати

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

Пребарај: #cosmonauticsday

当前筛选 #cosmonauticsday清除筛选

🚀 On April 12, 1961, at 09:07 Moscow time, the Vostok spacecraft with pilot-cosmonaut Yuri Gagarin on board blasted off from the Baikonur Cosmodrome, marking the beginning of the space age in the history of mankind. Yuri Gagarin spent 108 minutes in space, making a complete orbit around the Earth, and successfully landed. While in orbit, he maintained radio contact with Earth, made observations through a porthole, controlled the operation of the ship's systems, and carried out simple experiments. 📰 Even his wife did not know about this feat. The news about Yuri's flight came out only 55 minutes after the launch of the Vostok rocket, becoming the most quoted report in the world. Two days later, many thousands of people with flowers and welcome posters took to the streets of Moscow, honouring the cosmonaut who had arrived in the capital. At the end of April, our compatriot went on a foreign tour, travelling through more than 30 countries in two years, where he was welcomed as a hero. #CosmonauticsDay

О мероприятии по случаю Международного дня полета человека в космос 12 апреля 2024 года по случаю Дня космонавтики Временный поверенный в делах Российской Федерации в Румынии Е.С.Копнина возложила цветы к бюсту Ю.А.Гагарина, советского летчика-космонавта, первого человека в мировой истории, совершившего полёт в космическое пространство. В торжественном мероприятии в Бухаресте приняли участие представители дипломатического корпуса, аккредитованного в Румынии, бизнеса, соотечественники, румынские общественные организации и СМИ. Российский дипломат поздравила гостей с праздником, отмечаемым ежегодно в день первого полета человека в космос, знаменовавшего важнейший шаг в истории человечества, впервые покинувшего колыбель родной планеты. Она отметила объединяющую силу Международного дня космонавтики, когда представители множества стран отдают дань памяти и восхищения мужеством, талантом и самоотверженным трудом всех поколений ученых, конструкторов, летчиков, внесших вклад в изучение и мирное освоение космического пространства. Мероприятие открыло серию культурных акций Посольства, посвященных Дню космонавтики. В их числе – конкурс и выставка детского рисунка «Я рисую космос» и показ на румынском языке познавательного документального фильма «Космическая история России», предоставленного Ассоциацией планетариев России. Кроме того, вниманию всех, увлеченных космической тематикой, будут представлены в переводе на румынский язык драматическая кинолента «Вызов», первый художественный фильм, снятый в условиях невесомости на Международной космической станции, и исторический фильм «Время первых» о первом выходе человека в открытый космос, совершенном советским космонавтом А.А.Леоновым 18 марта 1965 года. ПРЕСС-СЛУЖБА ПОСОЛЬСТВА #CosmonauticsDay#ДеньКосмонавтики

Russian Embassy in Albania

@rusembalb · Post #6740 · 12.04.2025 г., 21:28

“Having orbited Earth in a spaceship, I saw for the first time how beautiful our planet is. People, let us preserve and increase this beauty and not destroy it!” — Yuri Alekseyevich Gagarin 🚀 The world changed forever in those moments when Vostok-1 launched from the Baikonur Cosmodrome, and Yuri #Gagarin became the first person in history to enter Earth’s orbit and circle our planet. This collective feat of the entire Soviet Union, its scientists, and cosmonauts marked the beginning of the space era in human history. 🌏 Before the launch of the spacecraft, Yuri Gagarin addressed the people of the entire planet with these inspiring words: “Dear friends, both familiar and unknown, compatriots, people of all countries and continents! In just a few minutes, a mighty spacecraft will carry me into the vast expanses of the universe. What can I say to you in these final moments before the launch? My entire life now seems to me like one beautiful moment. Everything I have lived through and accomplished was done for the sake of this moment. Am I happy to be embarking on this spaceflight? Of course, I am! After all, throughout history, it has been the highest happiness for people to participate in new discoveries. Now, only a few minutes remain until the launch. I want to say goodbye to you, my dear friends, as people always say to each other when setting off on a long journey. How I wish I could embrace you all — both those I know and those I don’t, those far away and those close by! Until we meet again!” #CosmonauticsDay#Gagarin#FirstInSpace

Russian Embassy in Cambodia

@russian_embassy_in_cambodia · Post #4255 · 12.04.2025 г., 12:57

“Having orbited Earth in a spaceship, I saw for the first time how beautiful our planet is. People, let us preserve and increase this beauty and not destroy it!” — Yuri Alekseyevich Gagarin 🚀 The world changed forever in those moments when Vostok-1 launched from the Baikonur Cosmodrome, and Yuri #Gagarin became the first person in history to enter Earth’s orbit and circle our planet. This collective feat of the entire Soviet Union, its scientists, and cosmonauts marked the beginning of the space era in human history. 🌏 Before the launch of the spacecraft, Yuri Gagarin addressed the people of the entire planet with these inspiring words: “Dear friends, both familiar and unknown, compatriots, people of all countries and continents! In just a few minutes, a mighty spacecraft will carry me into the vast expanses of the universe. What can I say to you in these final moments before the launch? My entire life now seems to me like one beautiful moment. Everything I have lived through and accomplished was done for the sake of this moment. Am I happy to be embarking on this spaceflight? Of course, I am! After all, throughout history, it has been the highest happiness for people to participate in new discoveries. Now, only a few minutes remain until the launch. I want to say goodbye to you, my dear friends, as people always say to each other when setting off on a long journey. How I wish I could embrace you all — both those I know and those I don’t, those far away and those close by! Until we meet again!” #CosmonauticsDay#Gagarin#FirstInSpace

Russian Consulate in Cape Town

@rusconct · Post #2440 · 12.04.2025 г., 12:32

“Having orbited Earth in a spaceship, I saw for the first time how beautiful our planet is. People, let us preserve and increase this beauty and not destroy it!” — Yuri Alekseyevich Gagarin 🚀 The world changed forever in those moments when Vostok-1 launched from the Baikonur Cosmodrome, and Yuri #Gagarin became the first person in history to enter Earth’s orbit and circle our planet. This collective feat of the entire Soviet Union, its scientists, and cosmonauts marked the beginning of the space era in human history. 🌏 Before the launch of the spacecraft, Yuri Gagarin addressed the people of the entire planet with these inspiring words: “Dear friends, both familiar and unknown, compatriots, people of all countries and continents! In just a few minutes, a mighty spacecraft will carry me into the vast expanses of the universe. What can I say to you in these final moments before the launch? My entire life now seems to me like one beautiful moment. Everything I have lived through and accomplished was done for the sake of this moment. Am I happy to be embarking on this spaceflight? Of course, I am! After all, throughout history, it has been the highest happiness for people to participate in new discoveries. Now, only a few minutes remain until the launch. I want to say goodbye to you, my dear friends, as people always say to each other when setting off on a long journey. How I wish I could embrace you all — both those I know and those I don’t, those far away and those close by! Until we meet again!” #CosmonauticsDay#Gagarin#FirstInSpace

Russian House Brussels-Europe

@rushousebrussels · Post #2989 · 30.03.2026 г., 12:45

📅April Programme at the Russian House Brussels We are pleased to present our April programme — a rich and diverse series of cultural, educational and artistic events. ✨ This month: — 🎨 Family space art workshop for children — 🎬 Space Documentary Film Days dedicated to Cosmonautics Day — 🎼 Concerts and musical evenings, including a special programme of the Bolshoi Theatre — 📚 Lectures and historical meetings — 🇷🇺 Russian language workshops and conversation club — 🎭 Theatre performance and film screenings for all ages 🖼 Throughout April, discover our exhibitions: — “The Amazing Earth” — “Energy of Space” by Sergey Kraynev — “Captain Cousteau in Russia” — “When Art Nouveau meets Artificial Intelligence” 📍 All events take place at the Russian House Brussels or online 🔗 Full programme and registration: rushouse.be We look forward to welcoming you! #RussianHouseBrussels#BrusselsEvents#Culture#RussianCulture#Art#Music#Cinema#Education#CosmonauticsDay#Brussels