Можно ли в 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
#prepositions
@fluencyinenglish
❇️Nouns commonly associated with particular prepositions❇️
1. At
Look/attempt/point/ age
Example: An attempt at integration of economic theories.
2. In
Changes/differences/increase/decrease
Example: Gender differences in risk-taking in financial decision-making.
3. Into
Insight/inquiry/research/investigation
Example: An investigation into sleep characteristics of children with autism
4. On
Work/research/influence/ emphasis/effect
Example: Genetic influence on smoking.
5. Of
Basis/idea/part/lack/exploration/means
Example: A computerized clinical decesion support system as a means of implementing depression guidelines.
6. For
Need/reason/basis/case/preference
Example: Assessing organizational culture: the case for multiple methods.
7. To
Relation/approach/ response/attention
Example: An approach to intercultural communication
8. To/towards
Attitude/tendency/move/progress
Example: Progress towards sustainable regional development.
9. Behind
Principle/rationale/assumption/logic
Example: Questioning the assumption behind art criticism.
10. Between
Relationship/difference/distinction
Example: The relationship between educational technology and studnet achievement in mathematics.
@fluencyinenglish
Due to heightened security measures in Moscow, the internet has been shut down.
🔻Residents of Russian regions have come up with a new holiday - the Day of the Runet without Muscovites.
🔻Please, before celebrating😉, mind the difference between Russian prepositions С(with) (+ Instrumental) and БЕЗ(without) (+Genitive):
• (Рунет) С москвичами
(Runet) WITH Muscovites
• (Рунет) БЕЗ москвичей
(Runet) WITHOUT Muscovites
📎Ничего(nothing) is written in one word.
#news
#prepositions
😎RCRussian | Support | Boost
• Я ДО работы (до + Genitive)
I'm BEFORE work
• Я НА работе (на + Prepositional)
I'm AT work
• Я ПОСЛЕ работы (после + Genitive)
I'm AFTER work
😉Мы?
🔻До и После details
🔻Genitive Singular
🔻Genitive Plural
🔻Prepositional Singular
🔻Prepositional Plural
#prepositions
#memes
🟠RCR | Support | Boost
#prepositions
#grammar
@fluencyinenglish
❇️نکاتی در مورد کاربرد حروف اضافه
⬅️با افعالی مثل resemble, discuss, lack, meet, approach, marry و enter از حروف اضافه استفاده نمی شود.
@fluencyinenglish
❌Henry and I discussed about the problem
✅Henry and I discussed the problem
👈من و هنری در مورد مشکل گفت و گو کردیم
❌He is going to marry with one of his classmates by the name of Rose
@fluencyinenglish
✅He is going to marry one of his classmates by the name of Rose
👈او قصد دارد با یکی از همکلاسیهایش به اسم رز ازدواج کند
❌We are approaching to the stadium
@fluencyinenglish
✅We are approaching the stadium
👈ما داریم به استادیوم نزدیک می شویم
❌I met with one of your old friends
✅I met one of your old friends
👈من با یکی از دوستان قدیمی ات ملاقات کردم
⬅️ با respect , expect , enjoy حرف اضافه به کار نمیبریم
@fluencyinenglish
❌I enjoy from this movie.
✅I enjoy this movie.
👈از این فیلم لذت بردم.
❌I expect of him to be good in class.
✅I expect him to be good in class.
@fluencyinenglish
👈از او انتظار داشتم که در کلاس خوب باشد.
❌I respect to him.
✅I respect him.
👈به او احترام میگذارم (برایش احترام قائلم)
⬅️ از حروف اضافه برای برخی از اصطلاحات رایج مربوط به زمان که با next, last, this, و one شروع می شوند استفاده نمی کنیم.
❌Let’s see each other on next Saturday
✅Let’s see each other next Saturday
@fluencyinenglish
👈بیا همدیگه رو شنبه بعد ببینیم
❌Meeting him in that morning is the worst memory I have
✅Meeting him that morning is the worst memory I have
👈ملاقات کردن او بدترین خاطره ایست که دارم
@fluencyinenglish
⬅️ از to قبل از کلمه home استفاده نمی شود
❌I’m going to home
✅ I’m going home
@fluencyinenglish
👈دارم میرم خونه
⬅️ بعد از after, before, against, at, by, on, of, about, instead of و without از ing برای افعال استفاده می شود.
@fluencyinenglish
❌I like to watch movies instead of read boring books
✅I like to watch movies instead of reading boring books
👈به جای خواندن کتاب های کسل کننده دوست دارم فیلم تماشا کنم
@fluencyinenglish
❌He went out without say anything
✅ He went out without saying anything
👈او بدون گفتن چیزی بیرون رفت.
@fluencyinenglish
Жан Клод Ван Дам в фильме "Некуда бежать".
Jean-Claude Van Damme in the movie "Nowhere to Run".
🔥Russian preposition ЧЕРЕЗ [che-riz]
🔢 To climb over something:
• Перелезть ЧЕРЕЗ забор
To climb OVER the fence
🔢 to go through something:
• Идти через лес
To walk through the forest
🔢 To go across something:
• Плыть через реку
To swim across the river
🔢 In some time:
• Я приду через час
I'll come in an hour
▶️ПО /ВДОЛЬ /МИМО /СКВОЗЬ забор
#prepositions
#grammar_tips
😎RCR | Support | Boost
#prepositions
#adjectives
@ieltsstrategies
@fluencyinenglish
صفات و حروفاضافی پرکاربرد
@ieltsstrategies
@fluencyinenglish
🔵Afraid + of/for
Janet had always been afraid of flying.
They tried to leave the country, afraid for their lives.
@ieltsstrategies
@fluencyinenglish
🔵Angry or annoyed + about/with
She felt a little annoyed about the delay
(About something)
I am not angry with you.
(With somebody)
@ieltsstrategies
@fluencyinenglish
🔵Anxious + for/to
Ministries are increasingly anxious about the money that has disappeared.
(Worried about).
I am anxious for the work to be done as soon as possible.(want sth very much)
@ieltsstrategies
@fluencyinenglish
🔵Bad or good at+for
She is good/bad at languages.
You should drink this. It is good/bad for you.(healthy or beneficial)
@ieltsstrategies
@fluencyinenglish
🔵Good + about/to/with
She felt good about winning the prize. (Pleased)
Tom was good to us.(kind)
He is good with his hands(skillful)
@ieltsstrategies
@fluencyinenglish
🔵Concerned + about / with
I am little concerned about your exam. (Worried)
This sections of the book is concerned with(about) adjectives.
@ieltsstrategies
@fluencyinenglish
🔵Glad + for/of
I am glad for you.
I would be glad to help.
@ieltsstrategies
@fluencyinenglish
🔵Pleased + about/at/with
He was pleased with/at the news.
He is really pleased with the car.(with sth)
She felt pleased with Paul.(with sb)
@ieltsstrategies
@fluencyinenglish
🔵Right + about/for
You are right about Tom.
We are sending her to school that we think is Right for her(suitable)
@ieltsstrategies
@fluencyinenglish
🔵Sorry + about/for
I am sorry about giving you a hard time.
I felt sorry for Susan(felt sympathy for sb)
@ieltsstrategies
@fluencyinenglish
https://t.me/joinchat/AAAAAEH8tC66WjhK5rdjUg
Она уже идёт?
Is she coming yet?
А теперь?
How about now?
Ну, теперь точно идёт?
Well, is she definitely coming now?
1. В углу
[v oog-loo]
In the corner
Location: inside the corner:
• Котёнок сидит в углу.
The kitten is sitting in the corner.
2. На углу
[na oog-loo]
On/at the corner
Location: on the exterior corner of a building/street:
• Давай встретимся на углу у метро.
Let's meet on the corner by the metro.
3. Из-за угла
[iz-za oog-la]
From behind/around the corner
Movement: appearing from behind the corner:
• Котёнок выскочил из-за угла.
The kitten jumped out from around the corner.
🎧🗣👇
#prepositions
#tricky_words
#useful_vocabulary
🟠RCR | Support | Boost
🤗Доброе утро, товарищи!Скучала! А вы?
играть НА 🆚️ играть В
🔢Играть НА (балалайке) (imperf. 1st conjugation verb)
[ig-rat' na (ba-la-lay-ke)]
To play the (balalaika)
• Ты только посмотри! Он играет на балалайке!
Just look! He's (it's) playing the balalaika!
🔻Here, играть signifies the act of producing music using an instrument.
💢Also:
• Играть НА (моих) нервах
[ig-rat' na (ma-ikh) ner-vakh]
To play on (my) nerves
🔻This implies a deliberate act of causing anxiety, frustration, or irritation.
🔢Играть В (футбол)
[ig-rat' f fut-bol]
To play (football)
• A они неплохо играют в футбол!
They play football pretty well!
🔻In this context, играть refers to participating in a competitive or recreational activity with rules.
А вы играете НА или В😉?Confess!
🎧🗣👇
#tricky_words
#useful_vocabulary
#prepositions
😎RCRussian | Support | Boost
👋Лёгкого понедельника, товарищи!
• Запутаться (perf., reflexive, 1st conjugation)
[za-pu-ta-tsa]
🔻Запутаться В ... (чём? + Prepositional case)
Origin:
This verb comes from the root пут-, which relates to путь (way, path).
Meanings:
🔢To get confused (mentally):
• Я запутался в правилах русской грамматики!
I got confused by the Russian grammar rules!
🔢 To become physically entangled:
• Я запутался в твоей пряже, Наташа!
I got tangled in your yarn, Natasha!
🔢To get lost (literally or figuratively):
• Мы запутались в лесу.
We got lost in the forest.
or
• Я запутался в своих чувствах!
I got lost in my feelings!
❗️Because it's reflexive, the subject is the one experiencing the confusion or entanglement.
🎧🗣👇А вы в чём запутались, товарищи😉?
#useful_vocabulary
#verbs
#prepositions
👋Приветствую!
По-моему 🆚 По моему
🔢По-моему
[pa mo-(y)i-mu]
From my point of view
🔻In this case, it is an introductory word that is separated by commas on both sides:
• По-моему, я вчера переборщил с Вискасом ...
In my opinion, I had too much Whiskas yesterday...
🔢По моему ... (+ masc./neut.noun in Dative)
[pa ma-yi-mu]
Down my ...
🔻We write the pronoun with the preposition without a hyphen:
• По моему телу пробежала дрожь, когда я увидел это фото.
A shiver ran down my body when I saw this photo.
❗️Mind the stress in these words and make up your own examples with the feline version of 'The Picture of Dorian Gray' in the video😉.
▶️Переборщить
Video:
™️Sonya cat
🎧🗣👇
#tricky_words
#grammar_tips
#prepositions
😎RCRussian | Support | Boost