Как записать список в файл python
Перейти к содержимому

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

  • автор:

Rukovodstvo

статьи и идеи для разработчиков программного обеспечения и веб-разработчиков.

Чтение и запись списков в файл в Python

В качестве сериализованных структур данных программисты Python интенсивно используют массивы, списки и словари. Для постоянного хранения этих структур данных требуется файл или база данных для работы. В этой статье описывается, как записать список в файл и как прочитать этот список обратно в память. Для записи данных в файл [/ writing-files-using-python /] и чтения данных из файла [/ read-files-with-python /] язык программирования Python предлагает стандартные методы write () и read. () для раздачи w

Время чтения: 5 мин.

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

Для записи данных в файл и чтения данных из файла язык программирования Python предлагает стандартные методы write() и read() для работы с одной строкой, а также writelines() и readlines() для работы с несколько строк. Кроме того, как pickle и json модуль также позволяют находить разумные способы работы с сериализованными наборами данных.

Использование методов чтения и записи

Для работы с символами (строками) отлично работают основные методы. Сохранить такой список построчно в файл listfile.txt можно следующим образом:

В строке 6 listitem , во-первых, расширяется переносом строки "\ n" и, во-вторых, сохраняется в выходном файле. Чтобы прочитать весь список из файла listfile.txt обратно в память, этот код Python показывает вам, как это работает:

Имейте в виду, что вам нужно удалить перенос строки с конца строки. В этом случае нам помогает то, что Python также допускает операции со списком для строк. В строке 8 приведенного выше кода это удаление просто выполняется как операция списка над самой строкой, которая сохраняет все, кроме последнего элемента. Этот элемент содержит символ «\ n», обозначающий разрыв строки в системах UNIX / Linux.

Использование методов Writelines и Readlines

Как упоминалось в начале этой статьи, Python также содержит два метода writelines() и readlines() для записи и чтения нескольких строк за один шаг соответственно. Чтобы записать весь список в файл на диске, код Python выглядит следующим образом:

Чтобы прочитать весь список из файла на диске, код Python выглядит следующим образом:

Приведенный выше листинг следует более традиционному подходу, заимствованному из других языков программирования. Чтобы написать его более питоническим способом, взгляните на приведенный ниже код:

После открытия файла listfile.txt в строке 5 восстановление списка происходит полностью в строке 6. Во-первых, содержимое файла считывается с помощью readlines() . Во-вторых, в for из каждой строки удаляется rstrip() . В-третьих, строка добавляется в список мест как новый элемент списка. По сравнению с приведенным выше листингом код намного компактнее, но может быть более трудным для чтения для начинающих программистов Python.

Использование модуля pickle

Различные методы, описанные до сих пор, хранят список таким образом, чтобы люди могли его прочитать. Если в этом нет необходимости, модуль pickle может вам пригодиться. Его dump() эффективно сохраняет список как поток двоичных данных. Во-первых, в строке 7 (в приведенном ниже коде) выходной файл listfile.data открывается для двоичной записи («wb»). Во-вторых, в строке 9
список сохраняется в открытом файле с помощью метода dump()

Следующим шагом мы читаем список из файла следующим образом. Во-первых, выходной файл listfile.data открывается в двоичном формате для чтения («rb») в строке 4. Во-вторых, список мест загружается из файла с помощью метода load()

Два примера здесь демонстрируют использование строк. Хотя, pickle работает со всеми типами объектов Python, такими как строки, числа, самоопределяемые структуры и любые другие встроенные структуры данных, которые предоставляет Python.

Использование формата JSON

Двоичный формат данных, который pickle специфичен для Python. Чтобы улучшить взаимодействие между различными программами, нотация объектов JavaScript ( JSON ) предоставляет простую в использовании и удобочитаемую схему и, таким образом, стала очень популярной.

В следующем примере показано, как записать список смешанных типов переменных в выходной файл с помощью модуля json. В строке 4 определяется основной список. Открыв выходной файл для записи в строке 7, метод dump() сохраняет основной список в файле, используя нотацию JSON.

Чтение содержимого выходного файла обратно в память так же просто, как запись данных. Соответствующий метод для dump() называется load() и работает следующим образом:

Заключение

Различные методы, показанные выше, варьируются от простой записи / чтения данных до сброса / загрузки данных через двоичные потоки с использованием pickle и JSON. Это упрощает постоянное хранение списка и чтение его обратно в память.

Writing List to a File in Python

In this article, you’ll learn how to write a list to a file in Python.

Often, we require storing a list, dictionary, or any in-memory data structure to persistent storage such as file or database so that we can reuse it whenever needed. For example, after analyzing data, you can store it in a file, and for the next time, that data can be read to use in an application.

There are multiple ways to write a Python list to a file. After reading this article, You’ll learn:

  • Write a list to a text file and read it in a Python program when required using a write() and read() method.
  • How to use Python’s pickle module to serialize and deserialize a list into a file. Serialize means saving a list object to a file. Deserialize means reading that list back into memory.
  • Use of built-in json module to write a list to a json file.

Table of contents

Steps to Write List to a File in Python

Python offers the write() method to write text into a file and the read() method to read a file. The below steps show how to save Python list line by line into a text file.

    Open file in write mode

Pass file path and access mode w to the open() function. The access mode opens a file in write mode.
For example, fp= open(r’File_Path’, ‘w’) .

Use for loop to iterate each item from a list. We iterate the list so that we can write each item of a list into a file.

In each loop iteration, we get the current item from the list. Use the write(‘text’) method to write the current item to a file and move to the next iteration. we will repeat this step till the last item of a list.

When we complete writing a list to a file, we need to ensure that the file will be closed properly. Use file close() method to close a file.

Example to Write List to a File in Python

Note: We used the \n in write() method to break the lines to write each item on a new line.

Output:

Below content got written in a file.

Text file after writing Python list into it

Text file after writing Python list into it

Example to Read List from a File in Python

Now, Let’s see how to read the same list from a file back into memory.

Output:

Write a list to file without using a loop

In this example, we are using a join method of a str class to add a newline after each item of a list and write it to a file.

The join() method will join all items in a list into a string, using a \n character as separator (which will add a new line after each list item).

Example:

If you want to convert all items of a list to a string when writing then use the generator expression.

Pickle module to write (serialize) list into a file

Python pickle module is used for serializing and de-serializing a Python object. For example, we can convert any Python objects such as list, dict into a character stream using pickling. This character stream contains all the information necessary to reconstruct the object in the future.

Any object in Python can be pickled and saved in persistent storage such as database and file for later use.

Example: Pickle and write Python list into a file

  • First import the pickle module
  • To write a list to a binary file, use the access mode ‘b’ to open a file. For writing, it will be wb , and for reading, it will be rb . The file open() function will check if the file already exists and, if not, will create one. If a file already exists, it gets truncated, and new content will be added at the start of a file.
  • Next, The pickle’s dump(list, file_object) method converts an in-memory Python object into a bytes string and writes it to a binary file.

Example:

Output:

Json module to write list into a JSON file

We can use it in the following cases.

  • Most of the time, when you execute a GET request, you receive a response in JSON format, and you can store JSON response in a file for future use or for an underlying system to use.
  • For example, you have data in a list, and you want to encode and store it in a file in the form of JSON.

Example:

In this example, we are going to use the Python json module to convert the list into JSON format and write it into a file using a json dump() method.

Output:

json file after writing list into it

json file after writing list into it

writelines() method to write a list of lines to a file

We can write multiple lines at once using the writelines() method. For example, we can pass a list of strings to add to the file. Use this method when you want to write a list into a file.

Here is the output we are getting

As you can see in the output, the file writelines() method doesn’t add any line separators after each list item.
To overcome this limitation, we can use list comprehension to add the new line character after each element in the list and then pass the list to the writelines method.

Example:

Output:

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

Запись списка в txt файл в питоне

Собственно как записать результат работы функции в txt файл?

insolor's user avatar

P.S Первый вариант хорош тем, что все действия выполняются в 1 строчку, но плох в плане того, что строчка конструируется целиком, и только лишь потом выполняется запись.

Чтобы записать в файл текстовое представление элементов списка через пробел в Питоне 3:

Если хочется каждый элемент на своей строчке напечатать:

Можно руками отформатировать (тот же результат):

Или напечатать по одному элементу за раз (тот же результат):

Чтобы сохранить в JSON формате:

Чтобы сохранить как csv:

Код продолжает работать даже если элементы содержат запятые, кавычки, новые строки внутри.

Reading and Writing Lists to a File in Python

Python programmers intensively use arrays, lists, and dictionaries as serialized data structures. Storing these data structures persistently requires either a file or a database to properly work.

In this article, we'll take a look at how to write a list to file, and how to read that list back into memory.

To write data in a file, and to read data from a file, the Python programming language offers the standard methods write() and read() for dealing with a single line, as well as writelines() and readlines() for dealing with multiple lines. Furthermore, both the pickle and the json modules allow clever ways of dealing with serialized data sets as well.

Using the read() and write() Methods

To deal with characters (strings) the basic read() and write() methods work excellently. Saving such a list line by line into the file listfile.txt can be done as follows:

The listitem is extended by a line break "\n" , firstly, and then stored into the output file. Now we can take a look at how to read the entire list from the file listfile.txt back into memory:

Keep in mind that you'll need to remove the line break from the end of the string. In this case, it helps us that Python allows list operations on strings, too. This removal is simply done as a list operation on the string itself, which keeps everything but the last element. This element contains the character "\n" that represents the line break on UNIX/Linux systems.

Using the writelines() and readlines() Methods

As mentioned at the beginning of this article, Python also contains the two methods — writelines() and readlines() — to write and read multiple lines in one step, respectively. Let's write the entire list to a file on disk:

To read the entire list from a file on disk we need to:

The code above follows a more traditional approach borrowed from other programming languages. Let's write it in a more Pythonic way:

Firstly, the file content is read via readlines() . Secondly, in a for loop from each line the line break character is removed using the rstrip() method. Thirdly, the string is added to the list of places as a new list item.

In comparison with the listing before the code is much more compact, but may be more difficult to read for beginner Python programmers.

Using the Joblib Module

The initial methods explained up to now store the list in a way that humans can still read it — quite literally a sequential list in a file. This is great for creating simple reports or outputting export files for users to further use, such as CSV files. However — if your aim is to just serialize a list into a file, that can be loaded later, there's no need to store it in a human-readable format.

The joblib module provides the easiest way to dump a Python object (can be any object really):

joblib remains the simplest and cleanest way to serialize objects in an efficient format, and load them later. You can use any arbitrary format, such as .sav , .data , etc. It doesn't really matter — both joblib and alternatives like pickle will read the files just fine.

Using the pickle Module

As an alternative to joblib , we can use pickle ! Its dump() method stores the list efficiently as a binary data stream. Firstly, the output file listfile.data is opened for binary writing ( "wb" ). Secondly, the list is stored in the opened file using the dump() method:

As the next step, we read the list from the file as follows. Firstly, the output file listfile.data is opened binary for reading ( "rb" ). Secondly, the list of places is loaded from the file using the load() method:

The two examples here demonstrate the usage of strings. Although, pickle works with all kinds of Python objects such as strings, numbers, self-defined structures, and every other built-in data structure Python provides.

Advice: For a detailed guide on pickling objects in general, read our "How to Pickle and Unpickle Objects in Python"!

Using the JSON Format

The binary data format pickle uses is specific to Python. To improve the interoperability between different programs the JavaScript Object Notation (JSON) provides an easy-to-use and human-readable schema, and thus became very popular for serializing files and sharing them over APIs.

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

The following example demonstrates how to write a list of mixed variable types to an output file using the json module. Having opened the output file for writing, the dump() method stores the basic list in the file using the JSON notation:

Reading the contents of the output file back into memory is as simple as writing the data. The corresponding method to dump() is named load() :

Conclusion

Different methods we've shown above range from simple writing/reading data up to dumping/loading data via binary streams using pickle and JSON. This simplifies storing a list persistently and reading it back into memory.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *