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 слични објави

Пребарај: #djangocon

当前筛选 #djangocon清除筛选
djangoproject

@djangoproject · Post #591 · 29.03.2018 г., 06:56

https://2018.djangocon.us/ Six days of talks, sprints, and tutorials in San Diego October 14-19 2018 #DjangoCon US has something for everyone, from the person who develops Django applications for a living to the person who just tinkers in their spare time. You'll discover details about a range of diverse applications that people from all over the world are building with Django, get a deeper understanding of concepts you’re already familiar with and discover new ways to use them, and have a lot of fun!

Hashtags

djangoproject

@djangoproject · Post #590 · 29.03.2018 г., 06:46

https://2018.djangocon.eu/ #DjangoCon Europe 2018 in Heidelberg May 23-27, 2018 · Heidelberg, Germany We are trying very hard to make this conference enjoyable to you even before it has started. One of the things we hope will be helpful is this timeline. Please understand that this is a rough timeline – as we cannot see into the future, some things might move around, but we will communicate every noticable change in a blog post!

Hashtags

djangoproject

@djangoproject · Post #371 · 04.07.2017 г., 14:47

https://2017.djangocon.us/news/tutorial-announcement/ #djangocon 🔹From 0 to 100 in Django 🔹How to React the Right Way (Django + React) 🔹Catching Tweets with Django + Django REST Framework 🔹Build a GraphQL API Using Django 🔹Build and Launch a Website on Wagtail, in Three Hours! 🔹Don’t Touch That Dial! An Introduction to Channels

Hashtags

djangoproject

@djangoproject · Post #370 · 04.07.2017 г., 14:18

https://2017.djangocon.us/ #djangocon Six days of talks, sprints, and tutorials by the community for the community. August 13–18 2017 🔸Flourishing FLOSS: Making Your Project Successful (Anna Ossowski) 🔸Functional Programming in an Imperative World. Maybe (Derik Pell) 🔸Understanding JavaScript Libraries via React and the React Ecosystem (Andrew Pinkham) 🔸Becoming a Polyglot: Lessons from Natural Language Learning (Rebekah E. Post) 🔸The Shy Person’s Guide to Tech Conferences (Ed Rivas) 🔸The CoC Committee Is Here for You (Erik Romijn) 🔸hunter2: A Symphony of Password Horror (Lilly Ryan) 🔸Files in Django (Josh Schneier) 🔸Programming Post-Progeny: A New Parent’s Perspective (Jacinda Shelly) 🔸Don’t Use My Grid System (Or Any Others) (Miriam Suzanne) 🔸Butter Smooth, Interactive Applications with Django and Websockets (Ganesh Swami) 🔸The 10 Commandments of Community Organizing (Jennifer Wadella) 🔸Exhausted Octopus Learns a Thing!! (Laura R. Webb) 🔸The Denormalized Query Engine Design Pattern (Simon Willison) 🔸Tasks: You Gotta Know How to Run ‘Em, You Gotta Know How to Safe ’Em (Filipe Ximenes)

Hashtags

djangoproject

@djangoproject · Post #369 · 04.07.2017 г., 14:08

https://2017.djangocon.us/ #djangocon Six days of talks, sprints, and tutorials by the community for the community. August 13–18 2017 🔸Saved You a Click (Or Three): Supercharging the Django Admin with Actions and Views (Liam Andrew) 🔸Django vs Flask (David “DB” Baumgold) 🔸End-to-End Django on Kubernetes (Josh Berkus) 🔸Going Rogue: How Code.org Created a Curriculum Development Platform without their Engineers (Josh Caldwell) 🔸Overcoming the Challenges of Mentoring (Kim Crayton) 🔸Stumbling Through Django and How Not to (Melanie Crutchfield) 🔸Maybe Not the Programmers They Deserved, but the Programmers They Needed (Jessica Deaton and Megan Will) 🔸GraphQL in the Wild (Arianne Dee) 🔸Accessibility Matters: Creating a Better Web (Lindsey Dragun) 🔸Taking Django Distributed (Andrew Godwin) 🔸The Monster on the Project (Tiberius Hefflin) 🔸Python & Spreadsheets: 2017 Edition (Kojo Idrissa) 🔸Type UWSGI; Press Enter; What Happens? (Philip James) 🔸Serverless Django (Rich Jones) 🔸Live long and refactor :vulcan_salute: (Sana Javed) 🔸Preventing Headaches with Linters and Automated Checks (Flávio Junior) 🔸Autopsy of a Slow Train Wreck: the Life and Death of a Django Startup (Russell Keith-Magee) 🔸The Beauty of ViewSets in Django Rest Framework (Buddy Lindsey, Jr.) 🔸Getting the most out of Django’s User Model (Julia M Looney) 🔸Alexa… (Heather Luna aka Heats) 🔸Write an API for Almost Anything (Or The Amazing Power and Flexibility of Django Rest Framework) (Charlotte Mays) 🔸The Power :zap: and Responsibility :sweat: of Unicode Adoption :sparkles: (Katie McLaughlin) 🔸Practical Unit Testing in Django (Wayne Merry) 🔸Using Django, Docker, and Scikit-Learn to Bootstrap Your Machine Learning Project (Lorena Mesa) 🔸Get a Jumpstart on Collaboration and Code Review in GitHub (Katherine “Kati” Michel) 🔸Why Can’t Everyone Just Do What I Want Them To? Leadership, Management, and Working with People Who Don’t Think like You (Briana Morgan)

Hashtags

djangoproject

@djangoproject · Post #368 · 04.07.2017 г., 13:39

http://2017.djangocon.com.au/ #DjangoCon AU: August 4, 2017 #PyCon AU: August 5 - 6, 2017 Sprints: August 7 - 8, 2017 🔷Django and JavaScript: A long and complicated friendship 🔷Bowerbirds of Technology: Architecture and Operations at Less-Than-Facebook Scale 🔷Loop better: a deeper look at iteration in Python 🔷Oh, I Found a Security Issue 🔷Offline Django with Service Workers 🔷hunter2: A Symphony of Password Horror 🔷Multitenant applications: how and why 🔷Horrors of Distributed Systems 🔷Red User, Blue User, MyUser, auth.User