Как записать словарь в файл python

от admin

save dictionary python

How to make python save a dictionary to a file. These are small programs that allows you to create a dictionary and then, when running the program, it will create a file that contains the data in the original dictionary.

Given a dictionary such as:

  • Comma seperated value file (.csv)
  • Json file (.json)
  • Text file (.txt)
  • Pickle file (.pkl)

save dictionary as csv file

The csv module allows Python programs to write to and read from CSV (comma-separated value) files.

CSV is a common format used for exchanging data between applications. The module provides classes to represent CSV records and fields, and allows outputs to be formatted as CSV files.

In this format every value is separated between a comma, for instance like this:

You can write it to a file with the csv module.

The dictionary file (csv) can be opened in Google Docs or Excel

save dictionary to json file

Today, a JSON file has become more and more common to transfer data in the world. JSON (JavaScript Object Notation) is a lightweight data-interchange format.

JSON is easy for humans to read and write. It is easy for machines to parse and generate.

JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others.

JSON was originally derived from the JavaScript scripting language, but it is not limited to any one programming language.

If you want to save a dictionary to a json file

save dictionary to text file (raw, .txt)

The program below writes a dictionary to an text string. It uses the str() call to convert the dictionary to a text string. While it is easy to write as a text string, this format makes it harder to read the file.

You can save your dictionary to a text file using the code below:

save dictionary to a pickle file (.pkl)

The pickle module may be used to save dictionaries (or other objects) to a file. The module can serialize and deserialize Python objects.

In Python, pickle is a built-in module that implements object serialization. It is both cross-platform and cross language, meaning that it can save and load objects between Python programs running on different operating systems, as well as between Python running on different platforms.

The pickle module is written entirely in Python, and is available in CPython implementations, such as Jython or IronPython. To enable the loading of pickles in other Python modules, pickle supports being executed from the command line.

Save a Dictionary to a File in Python

This tutorial explains multiple methods to save a dictionary to a file in Python language. Methods include:

Please enable JavaScript

  • dump() function of pickle module of Python
  • save() function of NumPy library
  • dump() function of Python json module.

Save a Dictionary to File in Python Using the dump Function of the pickle Module

The code example below shows how we can use the dump() function of the pickle module to save the dictionary and read a dictionary from the saved file using the load() function. The dump() function of the pickle module needs the dictionary which we want to save, and the file object as parameters to save the dictionary as a .pkl file.

The below code example shows how to read the dictionary saved in a file, using the load() function. The load() function needs a file object as a parameter to load the dictionary from the .pkl file.

Save a Dictionary to File in Python Using the save Function of NumPy Library

The save() function of the NumPy library can also save a dictionary in a file. In order to save the dictionary as a .npy file, the save() function requires the file name and dictionary which we want to save, as parameters to save the dictionary to a file.

The code example shows how to read the Python dictionary saved as .npy file. The load() function of NumPy library requires the file name and need to set allow_pickle parameter as True to load the saved dictionary from .npy file.

Save a Dictionary to File in Python Using the dump Function of the json Module

Another method to save a dictionary to file in Python is to use the dump() function of the json module. It also needs dict variable which we want to save, and file object as parameters to save the dictionary as .json file

Читать:
Как включить диспетчер задач через bat

Code example to read the dictionary saved as a file using the load function of the json module is shown below. The load() function needs file object as parameter to load the dictionary from the .json file.

Работа с файлами в формате CSV#

CSV (comma-separated value) — это формат представления табличных данных (например, это могут быть данные из таблицы или данные из БД).

В этом формате каждая строка файла — это строка таблицы. Несмотря на название формата, разделителем может быть не только запятая.

И хотя у форматов с другим разделителем может быть и собственное название, например, TSV (tab separated values), тем не менее, под форматом CSV понимают, как правило, любые разделители.

Пример файла в формате CSV (sw_data.csv):

В стандартной библиотеке Python есть модуль csv, который позволяет работать с файлами в CSV формате.

Чтение#

Пример чтения файла в формате CSV (файл csv_read.py):

Вывод будет таким:

В первом списке находятся названия столбцов, а в остальных соответствующие значения.

Обратите внимание, что сам csv.reader возвращает итератор:

При необходимости его можно превратить в список таким образом:

Чаще всего заголовки столбцов удобней получить отдельным объектом. Это можно сделать таким образом (файл csv_read_headers.py):

Иногда в результате обработки гораздо удобней получить словари, в которых ключи — это названия столбцов, а значения — значения столбцов.

Для этого в модуле есть DictReader (файл csv_read_dict.py):

Вывод будет таким:

До Python 3.8 возвращался отдельный тип упорядоченные словари (OrderedDict).

Запись#

Аналогичным образом с помощью модуля csv можно и записать файл в формате CSV (файл csv_write.py):

В примере выше строки из списка сначала записываются в файл, а затем содержимое файла выводится на стандартный поток вывода.

Вывод будет таким:

Обратите внимание на интересную особенность: строки в последнем столбце взяты в кавычки, а остальные значения — нет.

Так получилось из-за того, что во всех строках последнего столбца есть запятая. И кавычки указывают на то, что именно является целой строкой. Когда запятая находится в кавычках, модуль csv не воспринимает её как разделитель.

Иногда лучше, чтобы все строки были в кавычках. Конечно, в данном случае достаточно простой пример, но когда в строках больше значений, то кавычки позволяют указать, где начинается и заканчивается значение.

Модуль csv позволяет управлять этим. Для того, чтобы все строки записывались в CSV-файл с кавычками, надо изменить скрипт таким образом (файл csv_write_quoting.py):

Теперь вывод будет таким:

Теперь все значения с кавычками. И поскольку номер модели задан как строка в изначальном списке, тут он тоже в кавычках.

Кроме метода writerow, поддерживается метод writerows. Ему можно передать любой итерируемый объект.

Например, предыдущий пример можно записать таким образом (файл csv_writerows.py):

DictWriter#

С помощью DictWriter можно записать словари в формат CSV.

В целом DictWriter работает так же, как writer, но так как словари не упорядочены, надо указывать явно в каком порядке будут идти столбцы в файле. Для этого используется параметр fieldnames (файл csv_write_dict.py):

Указание разделителя#

Иногда в качестве разделителя используются другие значения. В таком случае должна быть возможность подсказать модулю, какой именно разделитель использовать.

How to save a dictionary to a file?

I have problem with changing a dict value and saving the dict to a text file (the format must be same), I only want to change the member_phone field.

My text file is the following format:

and I split the text file with:

When I try change the member_phone stored in d , the value has changed not flow by the key,

and how to save the dict to a text file with same format?

martineau's user avatar

12 Answers 12

Python has the pickle module just for this kind of thing.

These functions are all that you need for saving and loading almost any object:

In order to save collections of Python there is the shelve module.

Hadij's user avatar

Pickle is probably the best option, but in case anyone wonders how to save and load a dictionary to a file using NumPy:

10xAI's user avatar

Franck Dernoncourt's user avatar

We can also use the json module in the case when dictionaries or some other data can be easily mapped to JSON format.

This solution brings many benefits, eg works for Python 2.x and Python 3.x in an unchanged form and in addition, data saved in JSON format can be easily transferred between many different platforms or programs. This data are also human-readable.

Похожие статьи