Как написать bin файл

Бинарный файл или файл с расширением bin представляет собой закодированный текст. Он используется в прикладных программах и, как правило, содержит информацию о программном обеспечении. В данном типе фала можно сохранять любые данные.

Как создавать bin файл

Инструкция

Присвойте коду страницы проекта имя библиотеки классов, чтобы создать бинарный файл. Имена библиотеки классов – это «IO» имена, которые используются для чтения и записи файлов. Например, в начало строки программного кода вставьте следующую строку: Include System IO.

Создайте файловый поток, потом присвойте переменной двоичное значение. В результате будет создан bin файл, но он будет пустым. Бинарный файл можно создавать с любым расширением, но чаще всего используется расширение bin. Чтобы создать двоичный файл используйте следующий программный код:
FileStream file = new
FileStream(“C:\mybinaryfile.bin”, FileMode, Create)
BinaryWriter binarystream = new
BinaryWriter(file);

Пропишите в программном коде функцию записи двоичного файла. Для этого используйте команду Write. Эта функция автоматически производит кодировку значений в двоичном режиме, что избавит вас от повторного кодирования перед сохранением файла. Пример записи в двоичный файл: «binarystream Write («Мой первый двоичный файл»); binarystream Write (10);»

Закройте файл после того, как в нем будет сохранена вся необходимая информация. Учтите, что закрытие файла в программировании чрезвычайно важный процесс, поскольку он означает окончание процесса создания файла. Только после того как файл будет закрыт, он станет доступен для использования приложениями. Чтобы закрыть двоичный файл и сохранить его на диске, впишите в программный код следующее выражение: «binarystream.Close();».

Протестируйте работу созданного бинарного файла. Для этого запустите приложение, информацию о котором содержит созданный файл. Если все заложенные в него функции выполняются, то программный код составлен верно. В противном случае вам придется заново перепроверять вписанный код, а также информацию, помещенную в файл. Воспользуйтесь функцией отладки бинарного файла и повторите тестирование.

Войти на сайт

или

Забыли пароль?
Еще не зарегистрированы?

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

In this article, we will discuss how to create a binary file from the given text file. Before proceeding to the steps, let’s have an introduction of what are text files and binary files.

Text files: Text files store data in human-readable form and sequentially.

Binary files: Binary files store data in the form of bits/groups of bits (bytes) in sequence. These bits’ combinations can refer to custom data. Binary files can store multiple types of data, such as images, audio, text, etc.

Problem Statement: The task here is to read data from a text file and create a new binary file containing the same data in binary form.

Example: Suppose there are details of customers in a file named “Custdata.txt” and the task is to create a binary file named “Customerdb” by reading data from the text file “Custdata.txt”.

  • Each line of file “Custdata.txt” contains a record of one customer’s information.
  • A record has 3 attributes i.e., ID, Name, and Age.
  • Each record has a fixed length.

Let us assume that “Custdata.txt” has the following data-

ID Name Age
1 Annil 22
2 Ram 45
3 Golu 25
  • Let the record size, the number of bytes in a record = B.
  • If data for 3 customers is written to a disk file, then the file will contain 3 × B bytes.
  • If there are information about the customer record’s relative position “pos” in the file, then the customer’s information can be directly read.
  • pos* (B – 1) will be the record’s starting byte position.

There is no requirement, as such, to store all values in a record in text format. The internal format can be used to directly store values. An option that is good and can be taken as a choice is to define a structure for our record.

struct Customers 
{
    int ID;
    char name[30];
    int age;
}

The individual elements of structure customers can now be accessed by creating a structure variable cs as:

  1. cs.ID.
  2. cs.name.
  3. cs.age.

Let us look at the methods that would be required to read the text file and write in the binary file. The function required for reading is fscanf() and for writing is fwrite().

Reading: fscanf() function is used to read the text file containing the customer data.

Syntax:

int fscanf(FILE* streamPtr, const char* formatPtr, …);
This function reads the data from file stream and stores the values into the respective variables.

Parameters of fscanf():

  • streamPtr: It specifies the pointer to the input file stream to read the data from.
  • formatPtr: Pointer to a null-terminated character string that specifies how to read the input. It consists of format specifiers starting with %. Example: %d for int, %s for string, etc.

There is a need to include <cstdio> header file for using this function.

Writing: fwrite() function is used in the program to write the data read from the text file to the binary file in binary form. 

Syntax:

size_t fwrite(const void * bufPtr, size size, size_t count, FILE * ptr_OutputStream);
The fwrite() function writes “count” number of objects, where size of every object is “size” bytes, to the given output stream.

Parameters of write():

  • bufPtr: Pointer to the block of memory whose content is written (converted to a const void*).
  • size: The size in bytes of each object to be written.
  • count: The count of total objects to be read.
  • ptr_OutputStream: Pointer to a file specifying the output file stream to write to.

There is a need to include<cstdio> header file for using this function.

Algorithm: Below is the approach for the program for reading the text file and writing the content in the binary form to a binary file.

  • Open the input text file and the output binary file.
  • Until the end of the text file is reached perform the following steps:
    • Read a line from the input text file, into 3 variables using fscanf().
    • The structure variable is set to values for elements(to write the structure variable into the output file.
    • Write that structure variable to the output binary file using fwrite().
  • Close the input text file and the output binary file.

Below is the C++ program for the above approach:

C++

#include <cstdio>

#include <cstring>

#include <iostream>

using namespace std;

struct Customers {

    int ID;

    char name[30];

    int age;

};

int main()

{

    struct Customers cs;

    int rec_size;

    rec_size = sizeof(struct Customers);

    cout << "Size of record is: "

         << rec_size << endl;

    FILE *fp_input, *fp_output;

    fp_input = fopen("custdata.txt", "r");

    if (fp_input == NULL) {

        cout << "Could not open input file"

             << endl;

        return -1;

    }

    fp_output = fopen("Customerdb", "wb");

    if (fp_output == NULL) {

        cout << "Could not open "

             << "output file" << endl;

        return -1;

    }

    int id, a;

    char n[30];

    int count = 0;

    cout << endl;

    while (!feof(fp_input)) {

        fscanf(fp_input, "%d %s %d ",

               &id, n, &a);

        count++;

        cs.ID = id, strcpy(cs.name, n), cs.age = a;

        fwrite(&cs, rec_size, 1, fp_output);

        printf(

            "Customer number %2d has"

            " data %5d %30s %3d n",

            count, cs.ID,

            cs.name, cs.age);

    }

    cout << "Data  from file read"

         << " and printedn";

    cout << "Database created for "

         << "Customers infon";

    cout << "Total records written: "

         << count << endl;

    fclose(fp_input);

    fclose(fp_output);

    return 0;

}

Output:

Size of record is: 40

Customer number  1 has data     1                    Annil  22
Customer number  2 has data     2                      Ram  45
Customer number  3 has data     3                    Golu  25          
Data  from file read and printed
Database created for Customers info     
Total records written: 3

Explanation: There were 3 records in the file “custdata.txt” that were read, printed, and saved in the “Customerdb” file in binary mode.
The text file contains 3 fields in every line- ID, Name, and Age.
The first line of the text file contains-

 1                    Annil  22

This line is read from the file, i.e, the data of ID, Name, and Age are read and their values are assigned to the variables id, n, and a respectively. Now assign the values of these 3 variables to the data members:  ID, name[], and age of the structure variable cs respectively.
Now using fwrite(&cs, rec_size, 1, fp_output), write one cs object of size rec_size  to the binary file- ” fp_output” (binary mode).
This procedure continues for all the lines of text files until the end of the file is reached. After the execution of the program ends, the file “custdata.txt” will remain as it is, as it was opened in the read mode-

 1                         Annil  22
 2                           Ram  45
 3                          Golu  25

This data is read line by line and written to the file “Customerdb” in binary mode. The file “Customerdb” will have the contents in binary form, which is not readable. The file, when opened normally, looks like this :

In this article, we will discuss how to create a binary file from the given text file. Before proceeding to the steps, let’s have an introduction of what are text files and binary files.

Text files: Text files store data in human-readable form and sequentially.

Binary files: Binary files store data in the form of bits/groups of bits (bytes) in sequence. These bits’ combinations can refer to custom data. Binary files can store multiple types of data, such as images, audio, text, etc.

Problem Statement: The task here is to read data from a text file and create a new binary file containing the same data in binary form.

Example: Suppose there are details of customers in a file named “Custdata.txt” and the task is to create a binary file named “Customerdb” by reading data from the text file “Custdata.txt”.

  • Each line of file “Custdata.txt” contains a record of one customer’s information.
  • A record has 3 attributes i.e., ID, Name, and Age.
  • Each record has a fixed length.

Let us assume that “Custdata.txt” has the following data-

ID Name Age
1 Annil 22
2 Ram 45
3 Golu 25
  • Let the record size, the number of bytes in a record = B.
  • If data for 3 customers is written to a disk file, then the file will contain 3 × B bytes.
  • If there are information about the customer record’s relative position “pos” in the file, then the customer’s information can be directly read.
  • pos* (B – 1) will be the record’s starting byte position.

There is no requirement, as such, to store all values in a record in text format. The internal format can be used to directly store values. An option that is good and can be taken as a choice is to define a structure for our record.

struct Customers 
{
    int ID;
    char name[30];
    int age;
}

The individual elements of structure customers can now be accessed by creating a structure variable cs as:

  1. cs.ID.
  2. cs.name.
  3. cs.age.

Let us look at the methods that would be required to read the text file and write in the binary file. The function required for reading is fscanf() and for writing is fwrite().

Reading: fscanf() function is used to read the text file containing the customer data.

Syntax:

int fscanf(FILE* streamPtr, const char* formatPtr, …);
This function reads the data from file stream and stores the values into the respective variables.

Parameters of fscanf():

  • streamPtr: It specifies the pointer to the input file stream to read the data from.
  • formatPtr: Pointer to a null-terminated character string that specifies how to read the input. It consists of format specifiers starting with %. Example: %d for int, %s for string, etc.

There is a need to include <cstdio> header file for using this function.

Writing: fwrite() function is used in the program to write the data read from the text file to the binary file in binary form. 

Syntax:

size_t fwrite(const void * bufPtr, size size, size_t count, FILE * ptr_OutputStream);
The fwrite() function writes “count” number of objects, where size of every object is “size” bytes, to the given output stream.

Parameters of write():

  • bufPtr: Pointer to the block of memory whose content is written (converted to a const void*).
  • size: The size in bytes of each object to be written.
  • count: The count of total objects to be read.
  • ptr_OutputStream: Pointer to a file specifying the output file stream to write to.

There is a need to include<cstdio> header file for using this function.

Algorithm: Below is the approach for the program for reading the text file and writing the content in the binary form to a binary file.

  • Open the input text file and the output binary file.
  • Until the end of the text file is reached perform the following steps:
    • Read a line from the input text file, into 3 variables using fscanf().
    • The structure variable is set to values for elements(to write the structure variable into the output file.
    • Write that structure variable to the output binary file using fwrite().
  • Close the input text file and the output binary file.

Below is the C++ program for the above approach:

C++

#include <cstdio>

#include <cstring>

#include <iostream>

using namespace std;

struct Customers {

    int ID;

    char name[30];

    int age;

};

int main()

{

    struct Customers cs;

    int rec_size;

    rec_size = sizeof(struct Customers);

    cout << "Size of record is: "

         << rec_size << endl;

    FILE *fp_input, *fp_output;

    fp_input = fopen("custdata.txt", "r");

    if (fp_input == NULL) {

        cout << "Could not open input file"

             << endl;

        return -1;

    }

    fp_output = fopen("Customerdb", "wb");

    if (fp_output == NULL) {

        cout << "Could not open "

             << "output file" << endl;

        return -1;

    }

    int id, a;

    char n[30];

    int count = 0;

    cout << endl;

    while (!feof(fp_input)) {

        fscanf(fp_input, "%d %s %d ",

               &id, n, &a);

        count++;

        cs.ID = id, strcpy(cs.name, n), cs.age = a;

        fwrite(&cs, rec_size, 1, fp_output);

        printf(

            "Customer number %2d has"

            " data %5d %30s %3d n",

            count, cs.ID,

            cs.name, cs.age);

    }

    cout << "Data  from file read"

         << " and printedn";

    cout << "Database created for "

         << "Customers infon";

    cout << "Total records written: "

         << count << endl;

    fclose(fp_input);

    fclose(fp_output);

    return 0;

}

Output:

Size of record is: 40

Customer number  1 has data     1                    Annil  22
Customer number  2 has data     2                      Ram  45
Customer number  3 has data     3                    Golu  25          
Data  from file read and printed
Database created for Customers info     
Total records written: 3

Explanation: There were 3 records in the file “custdata.txt” that were read, printed, and saved in the “Customerdb” file in binary mode.
The text file contains 3 fields in every line- ID, Name, and Age.
The first line of the text file contains-

 1                    Annil  22

This line is read from the file, i.e, the data of ID, Name, and Age are read and their values are assigned to the variables id, n, and a respectively. Now assign the values of these 3 variables to the data members:  ID, name[], and age of the structure variable cs respectively.
Now using fwrite(&cs, rec_size, 1, fp_output), write one cs object of size rec_size  to the binary file- ” fp_output” (binary mode).
This procedure continues for all the lines of text files until the end of the file is reached. After the execution of the program ends, the file “custdata.txt” will remain as it is, as it was opened in the read mode-

 1                         Annil  22
 2                           Ram  45
 3                          Golu  25

This data is read line by line and written to the file “Customerdb” in binary mode. The file “Customerdb” will have the contents in binary form, which is not readable. The file, when opened normally, looks like this :

Создать бинарный файл и текстовый файл

04.05.2016, 15:53. Показов 24642. Ответов 1


Вот, к примеру, я написал программу для введения 5 чисел в текстовый файл, а как будет выглядеть программа бинарного файла?

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    int a;
    ofstream file("file.txt");
    for (int i = 0; i<5; i++)
    {
        cin >> a;
        file << a << endl;
    }
    system("pause");
    return 0;
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0




  1. Gnid

    Gnid

    New Member

    Публикаций:

    0

    Регистрация:
    28 янв 2006
    Сообщения:
    2
    Адрес:
    Ukraine

    вопрос, достойный мастера :)

    много читал надписи типа «а теперь из этого файла скомпилим бинарник…» Так как из обычного например текстового файла получить бинарник?

  2. Переименовать .txt в .bin :)

  3. Если исходник на MASM, то нужно как минимум 3 вещи:

    1. транслятор

    2. линкер

    3. способность разобраться в их многочисленных ключах.

    На fasm всё чуть проще — достаточно лишь транслятора (fasm) — набрать, к примеру,

    fasm.exe <name.asm> <name.exe>


  4. Gnid

    Gnid

    New Member

    Публикаций:

    0

    Регистрация:
    28 янв 2006
    Сообщения:
    2
    Адрес:
    Ukraine

    Alexey2005

    спасибо канэчна, но дело в том что я скомпилить и слинковать в экзешник все-таки смогу, а вот как получить бинарник?


  5. mix_mix

    mix_mix

    Михаил

    Публикаций:

    0

    Регистрация:
    8 окт 2005
    Сообщения:
    277
    Адрес:
    Токио

    Господи, бинарник и откомпиленная прога одно и тоже, тоже самое, что текст проги и исходник.

  6. Gnid

    — берешь my.txt, пишешь в нем слово BINARI, сохраняешь как my.bin

    — берешь my.asm, пишешь:

    Нажимаешь в фасме F9 (компилить)

    А потом сверяешь полученные разными способами 2 файла my.bin :)


WASM

Бинарные файлы. Примеры работы с бинарными файлами

В данной теме показано как можно сохранять данные в бинарных файлах без использования стандартных средств pickle или struct языка Python.


Содержание

  • 1. Понятие о бинарных файлах. Представление информации в бинарных файлах
  • 2. Запись/чтение списка, который содержит вещественные числа. Пример
  • 3. Запись/чтение кортежа, содержащего строки символов. Пример
  • 4. Запись/чтение множества, содержащего вещественные числа. Пример
  • 5. Запись/чтение двумерной матрицы строк заданного размера. Пример
  • 6. Запись/чтение словаря. Пример
  • 7. Копирование одного бинарного файла в другой
  • 8. Объединение двух бинарных файлов
  • Связанные темы

Поиск на других ресурсах:

1. Понятие о бинарных файлах. Представление информации в бинарных файлах

В языке Python существуют средства для работы с бинарными или двоичными файлами. Бинарные файлы используют строки типа bytes. Это значит при чтении бинарных данных из файла возвращается объект типа bytes.

Открытие бинарного файла осуществляется с помощью функции open(), параметр mode которой содержит символ ‘b’. Более подробно об открытии/закрытии бинарных файлов описывается здесь.

В отличие от текстовых, бинарные файлы не выполняют преобразования символов конца строки ‘n’.

Пример, демонстрирующий особенности представления информации в бинарных файлах.

# Python. Работа с бинарными файлами

# Открыть бинарный файл для чтения
f = open('myfile1.bin', 'rb')

# Получить одну строку из бинарного файла
d = f.read()

# Вывести эту строку.
# Будет получен вывод в виде строки символов
print("d = ", d) # d = b'x80x03]qx00(Kx01x88G@x07n=pxa3xd7ne.'

# Если вывести как отдельный символ,
# то будет выведен код символа - как целое число
print("d[5] = ", d[5]) # d[5] =   40
print("d[0] = ", d[0]) # d[0] =   128

# Использовать функцию bin для отдельного символа
print(bin(d[2])) # 0b1011101
f.close()

Результат работы программы

d =   b'x80x03]qx00(Kx01x88G@x07n=pxa3xd7ne.'
d[5] = 40
d[0] = 128
0b1011101

На основании примера выше можно сделать следующие выводы:

  • строка бинарных данных выводится как строка;
  • отдельный символ (элемент) бинарных данных представлен в виде 8-битных целых чисел.

 

2. Запись/чтение списка, который содержит вещественные числа. Пример
# Бинарные файлы. Запись/чтение списка вещественных чисел
# 1. Заданный список вещественных чисел
L = [1.5, 2.8, 3.3]

# 2. Запись файла
# 2.1. Открыть файл для записи
f = open('myfile3.bin', 'wb')

# 2.2. Обход списка и запись данных в файл
for item in L:
    # добавить символ 'n', чтобы можно было распознать числа
    s = str(item) + 'n'

    # Метод encode() - конвертирует строку в последовательность байт
    bt = s.encode()
    f.write(bt) # метод write() - запись в файл

# 2.3. Закрыть файл
f.close();

# 3. Считать список из бинарного файла 'myfile3.bin'
# 3.1. Создать пустой список
L2 = []

# 3.2. Открыть файл для чтения
f = open('myfile3.bin', 'rb')

# 3.3. Обход строк файла, конвертирование и добавление в список L2
for ln in f:
    x = float(ln) # взять число
    L2 = L2 + [x] # Добавить число к списку

# 3.4. Вывести список
print("L2 = ", L2) # L2 = [1.5, 2.8, 3.3]

# 3.5. Закрыть файл
f.close();

Результат работы программы

L2 = [1.5, 2.8, 3.3]

 

3. Запись/чтение кортежа, содержащего строки символов. Пример

В данном примере строки символов в бинарном файле разделяются символом ‘n’. Таким образом, можно записывать и читать информацию без потери ее структуры.

# Бинарные файлы. Запись/чтение кортежа, содержащего строки символов

# 1. Заданный кортеж со строками
T = ( 'abc', 'def', 'ghi', 'jk lmn')

# 2. Запись кортежа T в файл 'myfile5.bin'
# 2.1. Открыть файл для записи
f = open('myfile5.bin', 'wb')

# 2.2. Цикл обхода кортежа
for item in T:
    bt = (item + 'n').encode() # конвертировать (str + 'n') => bytes
    f.write(bt) # записать bt в файл

# 2.3. Закрыть файл
f.close();

# 3. Считать кортеж из бинарного файла 'myfile5.bin'
# 3.1. Открыть файл для чтения
f = open('myfile5.bin', 'rb')

# 3.2. Новый кортеж
T2 = ()

# 3.3. Прочитать данные из файла
for line in f:
    s = line.decode() # конвертировать bytes=>str
    s = s[:-1] # Убрать последний символ
    T2 = T2 + (s,) # Добавить строку s к кортежу

# 3.4. Вывести кортеж
print("T2 = ", T2)

# 3.5. Закрыть файл
f.close();

Результат работы программы

T2 = ('abc', 'def', 'ghi', 'jk lmn')

 



4. Запись/чтение множества, содержащего вещественные числа. Пример

Множество, которое содержит только однотипные объекты можно записать в файл. В данном примере записывается множество вещественных чисел.

# Бинарные файлы. Запись/чтение множества,
# которое содержит вещественные числа

# 1. Заданное множество
M = { 0.2, 0.3, 0.8, 1.2, 1.77 }

# 2. Запись множества M в файл 'myfile6.bin'
# 2.1. Открыть файл для записи
f = open('myfile6.bin', 'wb')

# 2.2. Цикл обхода множества
for item in M:
    s = str(item) + 'n' # конвертировать float=>str + 'n'
    bt = s.encode()     # конвертировать str=>bytes
    f.write(bt)         # записать bt в файл

# 2.3. Закрыть файл
f.close();

# 3. Считать множество из бинарного файла 'myfile6.bin'
# 3.1. Открыть файл для чтения
f = open('myfile6.bin', 'rb')

# 3.2. Новое множество
M2 = set()

# 3.3. Прочитать данные из файла
for line in f:
    x = float(line) # конвертировать bytes=>x
    M2 = M2.union({x}) # Добавить x к множеству

# 3.4. Вывести множество
print("M2 = ", M2)

# 3.5. Закрыть файл
f.close()

Результат работы программы

M2 = {0.2, 0.8, 0.3, 1.77, 1.2}

Вид файла myfile6.bin

0.2
0.8
1.77
0.3
1.2

 

5. Запись/чтение двумерной матрицы строк заданного размера. Пример

В примере матрица представлена в виде списка.

# Бинарные файлы. Запись/чтение матрицы, которая содержит строки

# 1. Заданная матрица строк размером 3*4
MATRIX = [ [ 'aa', 'ab', 'ac', 'ad'],
           [ 'ba', 'bb', 'bc', 'bd'],
           [ 'ca', 'cb', 'cc', 'cd'] ]

# 2. Запись матрицы MATRIX в файл 'myfile7.bin'
# 2.1. Открыть файл для записи
f = open('myfile7.bin', 'wb')

# 2.2. Сначала записать размер матрицы
m = 3
n = 4

# конвертировать m, n в строчный тип str
sm = str(m) + 'n'
sn = str(n) + 'n'

# конвертировать строку str в bytes
bm = sm.encode()
bn = sn.encode()

# записать размеры матрицы в файл
f.write(bm)
f.write(bn)

# 2.3. Цикл обхода матрицы
for row in MATRIX:
    # здесь нужно просто записать строки с символом 'n'
    for item in row:
        item = item + 'n'
        bt = item.encode() # str=>bytes
        f.write(bt)       # записать bt в файл

# 2.3. Закрыть файл
f.close();

# 3. Считать матрицу из бинарного файла 'myfile7.bin'
# 3.1. Открыть файл для чтения
f = open('myfile7.bin', 'rb')

# 3.2. Новая матрица
MATRIX2 = []

# 3.3. Прочитать данные из файла
# 3.3.1. Сначала прочитать размер
s = f.readline()
m2 = int(s)
s = f.readline()
n2 = int(s)

# 3.3.2. Цикл чтения строк и создание матрицы размером m2*n2
i = 0
while i < m2:   # m2 строк в матрице
    row = [] # одна строка списка
    j = 0
    while j < n2:
        bs = f.readline() # прочитать один элемент типа bytes
        s = bs.decode() # конвертировать bytes=>str
        s = s[:-1] # убрать 'n'
        row += [s]   # добавить к списку
        j = j+1

    MATRIX2 += [row] # добавить одну строку списка к матрице
    i = i+1

# 3.4. Вывести новую матрицу
i = 0
while i < m2:
    print("MATRIX2[", i, "] = ", MATRIX2[i])
    i = i+1

# 3.5. Закрыть файл
f.close()

Результат работы программы

MATRIX2[ 0 ] = ['aa', 'ab', 'ac', 'ad']
MATRIX2[ 1 ] = ['ba', 'bb', 'bc', 'bd']
MATRIX2[ 2 ] = ['ca', 'cb', 'cc', 'cd']

Вид файла myfile7.txt

3
4
aa
ab
ac
ad
ba
bb
bc
bd
ca
cb
cc
cd

 

6. Запись/чтение словаря. Пример

Пусть задан некоторый словарь, который нужно записать в бинарный файл.

# Бинарные файлы. Запись/чтение словаря
# 1. Заданный словарь. Пары типа str:int
D = { 'One':1, 'Two':2, 'Three':3, 'Four':4 }

# 2. Запись словаря D в файл 'myfile8.bin'
# 2.1. Открыть файл для записи
f = open('myfile8.bin', 'wb')

for key in D: # обход словаря
    # взять значение value
    value = D[key]

    # Записать последовательно key, затем value
    svalue = str(value) + 'n' # сначала конвертировать value в строку
    skey = key + 'n' # к строке key добавить 'n'

    # Конвертировать key:svalue из строки в bytes
    b_key = skey.encode()
    b_svalue = svalue.encode()

    # записать b_key, b_svalue в файл
    f.write(b_key)
    f.write(b_svalue)

# 2.3. Закрыть файл
f.close();

# 3. Считать словарь из бинарного файла 'myfile8.bin'
# 3.1. Открыть файл для чтения
f = open('myfile8.bin', 'rb')

# 3.2. Новый словарь, который будет прочитан из файла
D2 = dict()

# 3.3. Прочитать весь файл сразу
b_strings = f.readlines() # b_strings - список строк типа bytes

# 3.4. Обойти список b_strings.
#     Сначала читается ключ, затем значение и т.д.
fkey = True # если True, то читается ключ, иначе читается значение
for item in b_strings:
    if fkey: # проверка, если читается ключ
        skey = item.decode() # конвертировать bytes=>str
        key = skey[:-1] # убрать 'n'
        fkey = False
    else:
        svalue = item.decode() # конвертировать bytes=>str
        value = int(svalue) # конвертировать str=>int
        D2[key] = value # добавить к словарю
        fkey = True # указать, что на следующей итерации будет ключ

# 3.5. Вывести словарь
print("D2 = ", D2)

# 3.6. Закрыть файл
f.close()

Результат работы программы

D2 = {'One': 1, 'Two': 2, 'Three': 3, 'Four': 4}

Вид файла myfile8.txt

One
1
Two
2
Three
3
Four
4

 

7. Копирование одного бинарного файла в другой
# Бинарные файлы. Копирование файлов

# 1. Открыть файлы
f1 = open('myfile8.bin', 'rb') # файл - источник, открывается для чтения
f2 = open('copyfile8.bin', 'wb') # файл - копия

# 2. Считать файл f1 в список строк bstrings
bstrings = f1.readlines()

# 3. Записать список строк bstrings в файл f2
f2.writelines(bstrings)

# 4. Закрыть файлы
f1.close()
f2.close()

 

8. Объединение двух бинарных файлов. Пример

В примере реализована операция объединения двух файлов в результирующий третий файл. Сначала данные с файлов-источников считываются в списки. Затем происходит конкатенация этих списков и запись результирующего списка в файл результата.

# Объединение файлов myfile1.bin+myfile2.bin => myfile3.bin
# 1. Открыть файлы для чтения
f1 = open('myfile1.bin', 'rb')
f2 = open('myfile2.bin', 'rb')

# 2. Считать файлы в списки L1, L2
L1 = f1.readlines()
L2 = f2.readlines()

# 3. Объединить списки
L3 = L1 + L2

# 4. Закрыть файлы myfile1.bin, myfile2.bin
f1.close()
f2.close()

# 5. Открыть файл myfile3.bin для записи
f3 = open('myfile3.bin', 'wb')

# 6. Записать строки в файл
f3.writelines(L3)

# 7. Закрыть результирующий файл
f3.close()

 


Связанные темы

  • Файлы. Общие понятия. Открытие/закрытие файла. Функции open(), close()
  • Примеры работы с текстовыми файлами

 


Понравилась статья? Поделить с друзьями:
  • Как написать biginteger
  • Как написать bewerbung на немецком
  • Как написать because сокращенно
  • Как написать beautiful
  • Как написать bat файл для копирования файлов