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

Резултати

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

Пребарај: #ecology

当前筛选 #ecology清除筛选
Earth&Climate Tech

@earth_climate_tech · Post #296 · 19.05.2023 г., 23:18

​​Мусорная экосистема в Тихом Океане Вау. Согласно исследованиям опубликованым в журнале BLOS Biology Большое Тихоокеанское Мусорное Пятно (Great Pacific garbage patch) является процветающим домом для целого ряда организмов. Размер Тихоокеанского мусорного пятна, сформированного океанскими течениями, около 1.6 миллионов квадратных километров 😱. Водоворот системы собирает мусор со всей северной части Тихого океана. Отходы подхватываются поверхностными течениями и постепенно перемещаются к центру водоворота, который не выпускает мусор за свои пределы. Пластиковые отходы в этом регионе хорошо задокументированы, но мало что известно о плавающих океанских существах, таких как медузы или ракообразные, например. Так вот в статье с названием "High concentrations of floating neustonic life in the plastic-rich North Pacific Garbage Patch" описывается как авторы плавали 80 дней по этому мусорному континенту и собрали образцы воды, организмов и пластика. Они обнаружили, что плотность плавающей жизни была выше в центральной части мусорного пятна, чем на ее периферии. Еще есть положительная связь между численностью организмов и количеством плавающего пластика. То есть вероятно образовалась антропогенная мусорная экосистема 🌊🍥🐠. #ecology#climate

Bali News

@balinews · Post #542 · 11.12.2025 г., 11:20

🗑️ Bali’s biggest landfill Suwung will close on December 23 Right before peak season! 📰 The governor insists the island is ready for the “green era,” but lawmakers and environmentalists are panicking: the new PSEL waste-processing plant still isn’t operational, and local TPS3R facilities can handle only about one-third of the daily 1,000+ tons of waste. ♻️ What will happen to the rest? Residents are being told to quickly learn to sort trash or get used to garbage bags piling up under their windows. #environment#ecology@BaliNews

Trump's Ear

@trumpsear_tg · Post #2147 · 13.02.2026 г., 14:59

Trump canceled a key point of the US climate policy, calling greenhouse gases harmless. US President Donald Trump has achieved the cancellation of the decision on which the American climate policy has been based since 2009. The U.S. Environmental Protection Agency (EPA) has invalidated the Obama-era conclusion that carbon dioxide and other greenhouse gases pose a threat to public health and well-being. It was on this norm that the key climate restrictions under the Clean Air Act were based, from emission limits for cars to requirements for power plants and industry. Trump and EPA chief Lee Zeldin called the move "the largest deregulation in American history." According to Trump, the previous rules were "disastrous," hurting the auto industry and "inflating prices for consumers." Environmentalists call the cancellation a historic setback and the biggest blow to the United States' ability to combat climate change. #Trump#Ecology#ClimateChanges 👂More on Trump's Ear ⚠️

Amazing Geography 🌍

@amazingeo · Post #173 · 04.09.2025 г., 09:12

🌍 The Eastern Arc Mountains in East Africa are a biodiversity hotspot where 75% of the area's plant species exist nowhere else on Earth—making it one of the planet’s most unique natural vaults. ✨ #biodiversity⚡#conservation⚡#ecology⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography🌍 ​

Interesting Planet 🌍

@interesting_planet_facts · Post #965 · 25.10.2025 г., 22:11

🌎 Cleaning up plastic from the ocean is getting high-tech—autonomous drones and floating barriers are now used to collect debris before it breaks down. The Ocean Cleanup project, for example, reported removing over 200,000 kilograms of plastic from the Great Pacific Garbage Patch by 2023. ✨ #ecology⚡#technology⚡#ocean 👉subscribe Interesting Planet 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #590 · 24.01.2026 г., 12:31

🌍 The Eastern Himalayas are a biodiversity hotspot with over 10,000 plant species, and nearly a quarter of them are found nowhere else, despite covering less than 2% of India’s total area. ✨ #biodiversity⚡#Himalayas⚡#ecology⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #706 · 03.05.2026 г., 20:31

🌍 Some freshwater wetlands form floating islands—mats of living plants thick enough to walk on. These islands create unique microhabitats and drift slowly across lakes or shallow wetlands. ✨ #wetlands⚡#freshwater⚡#ecology⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

Amazing Geography 🌍

@amazingeo · Post #434 · 04.11.2025 г., 20:31

🌍 Some grassland plants grow deep roots reaching over 2 meters underground. These roots help the plants survive drought and anchor soil, making grasslands some of the most erosion-resistant landscapes. ✨ #grasslands⚡#savanna⚡#ecology⚡#geography⚡#nature⚡#earth 👉subscribe Amazing Geography 👉more Channels ​

🔔 Встреча в рамках проекта «Бизнес мастер-класс» 📣 Уважаемые профессора-преподаватели, слушатели и гости! Приглашаем вас на очередную встречу в рамках проекта «Бизнес мастер-класс». 💼 Очередным гостем-докладчиком проекта выступит Алексей Волков, Национальный координатор GEF SGP в Узбекистане. 🚻 Тема встречи: «Внедрение инновационных ресурсосберегающих практик: Принципы и опыт проектов Программы малых грантов Глобального экологического фонда». 🗓 Дата: 25 октября 2024 года ⏳ Время: 10:30 📞 +998 71 239-03-14 📍 Адрес: Высшая школа бизнеса и предпринимательства (5-й этаж) #GraduateSchool#Global#Ecology#Grant 🔝Web-site |🔝Facebook | 🔝Instagram | 🔝Youtube

🔔 "Biznesda mahorat darslari" loyihasi doirasida uchrashuv 📣 Hurmatli professor-o‘qituvchilar, tinglovchilar va mehmonlar! Sizlarni “Biznesda mahorat darslari” loyihasi doirasida bo‘lib o‘tadigan uchrashuvga taklif etamiz! 🤵 Loyihaning navbatdagi mehmon ma’ruzachisi Aleksey Volkov GEF SGP O‘zbekistondagi Milliy koordinatori. 🚻 "Innovatsion resurslarni tejash amaliyotini joriy etish: Global Ekologik Fond Kichik Grantlar Dasturi loyihalari tamoyili va tajribasi" mavzusidagi uchrashuvga marhamat. 🗓Sanasi: 25-oktyabr 2024-yil ⏰Vaqti: 10.30 ☎️ +998 71 239-03-14 📍Manzil: Biznes va tadbirkorlik oliy maktabi (5-qavat) #GraduateSchool#Global#Ecology#Grant 🔝Web-site |🔝Facebook | 🔝Instagram | 🔝Youtube

Interesting Planet 🌍

@interesting_planet_facts · Post #1372 · 13.04.2026 г., 12:11

🌎 Advances in carbon capture technology could help slow climate change by removing CO2 directly from the air. Direct air capture plants use chemical filters to collect carbon dioxide for storage underground or reuse in products. As of 2023, the largest facility can capture up to 4,000 metric tons of CO2 per year. ✨ #ecology⚡#climate⚡#technology 👉subscribe Interesting Planet 👉more Channels ​

Interesting Planet 🌍

@interesting_planet_facts · Post #1255 · 25.01.2026 г., 12:11

🌎 Urban forests, groups of trees specially planted in cities, can lower summer air temperatures by up to 5°C, improve air quality, and support local biodiversity. By 2030, the UN aims to help 500 cities plant urban forests to make urban life healthier and more sustainable. ✨ #ecology⚡#technology⚡#climate 👉subscribe Interesting Planet 👉more Channels ​

123•••67
ПретходнаСтраница 1 од 7Следна