Как считать файл в массив питон
In this article, we are going to see how to read text files into lists in Python.
File for demonstration:
Example 1: Converting a text file into a list by splitting the text on the occurrence of ‘.’.
We open the file in reading mode, then read all the text using the read() and store it into a variable called data. after that we replace the end of the line(‘/n’) with ‘ ‘ and split the text further when ‘.’ is seen using the split() and replace() functions.
read(): The read bytes are returned as a string. Reads n bytes, or the full file if no n is given.
split(): The split() method creates a list from a string. The separator can be specified; the default separator is any whitespace.
Syntax: string.split(separator, maxsplit)
replace(): The replace() method substitutes one phrase for another.
Считываем числовые данные из файла на Python
В данной статье речь пойдет о простой на первой взгляд задаче — считывании числовых данных из текстовых файлов на Python. В сети можно найти десятки способов решения этой задачи, однако эти алгоритмы оказываются малоэффективными при работе с большим объемом данных. В данной статье будут разобраны самые популярные методики, а также произведено сравнение их скорости работы.
Введение
Когда я только начинал изучать Python, главным помощником в работе для меня, как наверное и для большинства программистов, был Stack Overflow. Я почерпнул оттуда много полезной информации, в том числе и о работе с файлами. Однако даже такая тривиальная задача, как оказалось, имеет несколько различных решений, отличающихся друг от друга простотой реализации и скоростью работы.
Большинство предложенных методов предполагают чтение файла построчно с дальнейшим разбиением на блоки и их преобразованием из строкового типа в числовой, поскольку Python в отличии от C/C++ работает с файлами как с массивом строк. Выполнить последовательное чтение данных в массив без преобразования типов, как это можно сделать в C/C++, стандартными средствами языка невозможно (насколько мне известно), и это существенно увеличивает время работы программы при обработке больших объемов данных.
Способы чтения данных из файла
Как уже было сказано выше, файлы в Python представляют собой массив строк, поэтому все найденные методы можно символически поделить на два типа в зависимости от используемого подхода:
- построчное считывание с разбиением и преобразованием типов
- использование библиотек, которые средствами других языков (например, C/C++) считывают файл и передают полученные данные интерпретатору Python
Ниже представлена подборка самых популярных методов чтения числовых данных на Python, отмеченных сообществом Stack Overflow как «best answer».
Способ 1 — построчное считывание с преобразованием
Самый популярный и простой вариант. Заключается в построчном чтении с разбиением полученной строки на блоки, которые затем преобразуются к необходимому типу данных (в данном случае float) и добавляются к заранее созданному списку.
Способ 2 — преобразование при помощи map
Способ аналогичен предыдущему, за исключением того, что преобразованием данных из строкового формата в числовой занимается функция map.
Способ 3 — с использованием регулярного выражения
Данный способ можно назвать стрельбой из пушки по воробьям, однако у него все же есть свои плюсы: если данные в файле расположены хаотично и отсутствует постоянная структура, то функции split невозможно задать конкретный разделитель и для решения задачи можно использовать регулярное выражение, которое найдет в строке все числа, несмотря на их расположение и наличие разделителей.
Способ 4 — с использованием CSV Reader
Если данные записаны в виде матрицы с постоянными разделителями, то выполнить их чтение можно при помощи модуля CSV Reader, указав в качестве параметра значение разделителя.
Способ 5 — Numpy loadtxt
Библиотека Numpy предоставляет широкий набор модулей и функций для обработки числовых данных, в том числе и для чтения массивов из файлов. Одна из реализаций возможна с помощью функции loadtxt, результат работы которой будет записан в numpy.array.
Способ 6 — Numpy genfromtxt
Данный способ не сильно отличается от предыдущего, за исключением того, что genfromtxt предоставляет более широкий набор входных параметров: указание различных типов данных для каждого из столбцов, передача ключей для создания ассоциативного массива и так далее.
Способ 7 — Pandas read_csv
Pandas — мощная библиотека для обработки данных на Python. В данном примере рассматривается только чтение данных, но её возможности этим не ограничены. Метод read_csv предоставляет широкий набор входных параметров, а также показывается высокую скорость работы даже при работе с большими объемами данных.
Методы тестирования скорости чтения
Для тестирования скорости чтения числовых данных были сгенерированы 7 тестовых файлов, содержащих 5 столбцов и 10, 100, 1 000, 10 000, 100 000, 1 000 000 и 10 000 000 строк случайных чисел формата float. Размер самого большого файла составил 742 Мб.
Для измерения времени работы программы использовалась функция time. Существует мнение, что измерять с её помощью время работы некорректно. Однако в данном случае меня интересовало работа с большими объемами данных, когда время работы программы составляло несколько десятков секунд. В таком случае отклонение в полсекунды вносило погрешность менее 1%.
Сравнение с компилируемыми языками программирования
Программы, созданные на компилируемых языках программирования, работают быстрее, чем их аналоги, написанные на интерпретируемых языках. Мне было интересно сравнить скорость чтения каждого метода с Fortran и C++ — самыми популярными языками в научном программировании, с которыми мне также приходится иметь дело в силу специфики моей работы.
Fortran
Несмотря на то, что Fortran считается устаревшим языком, он все еще очень популярен в научном программировании благодаря простоте написания кода, скорости обмена данных и обширном количестве библиотек, созданных за последние полвека.
Например, считать числовую матрицу из файла можно всего за 3 строчки кода при условии корректности входных данных.
Дискуссии о том, что лучше: Fortran или C++ ведутся уже давно, даже среди авторов EasyCoding этот спор возникал несколько раз, поэтому мне было еще интересней протестировать чтение матриц на данном языке.
Результаты тестирования
В ходе эксперимента были протестированы 7 программ на языке Python и по одной на Fortran и C++, код которых представлен выше. Запуск программ осуществлялся на компьютере с Intel Core i5 2.7 GHz и 8 Гб оперативной памяти.
Для запуска программ использовались следующие интерпретаторы и компиляторы:
GNU Fortran (GCC) 6.1.0
Для каждой программы проводилась серия испытаний и измерялось время работы, после чего записывался результат в виде среднего арифметического полученных данных. В таблице ниже жирным в каждой строке выделено наименьшее время работы в зависимости от способа чтения и размера входного файла.
| Число строк | Способ | ||||||||
|---|---|---|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | Fortran | C++ | |
| 10 | 0.048 | 0.048 | 0.045 | 0.044 | 0.173 | 0.216 | 0.479 | 0.005 | 0.005 |
| 100 | 0.053 | 0.052 | 0.05 | 0.048 | 0.185 | 0.223 | 0.511 | 0.007 | 0.006 |
| 1 000 | 0.056 | 0.053 | 0.053 | 0.052 | 0.187 | 0.233 | 0.6 | 0.01 | 0.01 |
| 10 000 | 0.085 | 0.076 | 0.096 | 0.083 | 0.305 | 0.292 | 0.636 | 0.032 | 0.041 |
| 100 000 | 0.414 | 0.403 | 0.561 | 0.482 | 1.537 | 0.874 | 0.796 | 0.244 | 0.363 |
| 1 000 000 | 3.835 | 4.502 | 6.086 | 5.276 | 13.607 | 6.754 | 1.763 | 2.584 | 3.662 |
| 10 000 000 | 47.931 | 156.944 | 137.398 | 144.75 | 162.724 | 85.642 | 13.632 | 25.652 | 36.622 |
В ходе данного исследования были протестированы 7 самых популярных варианта чтения числовых матриц на языке Python, предложенными пользователями сайта Stack Overflow и отмеченными сообществом как «верный ответ». Как видно из таблицы с результатами, скорость работы программ не сильно отличается при использовании способов 1-4 на небольших объемах данных. Это связано с тем, что интерпретатор не тратит время на инициализацию сторонней библиотеки, как в методах 5-7.
Однако при увеличении объема входных данных лучше всех себя показал метод 7 с использованием библиотеки Pandas, который даже обогнал по скорости чтения данных языки C++ и Fortran.
Также из результатов теста можно видеть, что программа на Fortran справилась с чтением данных быстрей аналога на C++, что еще раз доказывает его превосходство над самым популярным языком программирования в мире.
10 commentaries to post
Наконец, нашел, что искал. Способ 6 — Numpy genfromtxt, который предоставляет более широкий набор входных параметров: указание различных типов данных для каждого из столбцов, передача ключей для создания ассоциативного массива и так далее.
Спасибо. Сэкономили время на поиск единственного, что нужно для моих вычислений по таблице «тексты-слова»…
ошибка в таблице ! 0.044 не меньше чем 0.005 а больше почти в 9 раз!
Нет ошибки. Автор сравнивал скорости Python решений.
С++, который обгонит всё перечисленное:
Причем не особо кошерная реализация. Но соответствует предоставленному коду.
Кошерная реализация это:
Спасибо за приведенное полезное сравнение. Не хватает сравнения скорости записи (в рам для точности)
К способу 6:
ModuleNotFoundError: No module named ‘numpy’
Ругается на import в начале
Необходимо установить соответствующую библиотеку numpy либо из репозиториев, либо посредством pip.
2 способ выдает:
[/, /, /]
при числах в файле:
1 2 3
4 5 6
7 8 9
Что не так?
Проверьте версию интерпретатора Python. В 3.7 работает нормально.
На С++ вы читали потоками, это медленно. Надо было попробовать функциями ввода вывода,fopen, fclose, fread должно быть быстрее. В С++ тоже несколько способов. Могло получиться сопоставимо с лучшим результатом.
9 ways to convert file to list in Python
In this post, we are going to learn 9 ways to convert file to list in Python. We will learn all these ways with code examples. We will take a sample text file with some data in it and then we will load the file data to a Python list. So let us begin with our tutorial.
Sample File : samplefile.txt’
This is the sample file that we are using in the code example. It exists in the current directory.
1. Pathlib to Convert text file to list Python
In Python 3.4. , we can use the Pathlib module to convert a file to a list. This is a simple way to convert a file to a list. In this example, we will use the read_text() method to read the file and the splitlines() method for the splitting of lines.
Program Example
Most Popular Post
2. For Loop to split file to list Python
In this example, We are iterating over each line of a file using for loop and appending each line to the list by removing the special new character(\n) using the strip() method.
Program Example
4. Readline() to create list from text file
The file readlines() method returns a list of file lines, separated by the newline character(\n). So here we are iterating over lines of a file and using the strip() method to remove the newline character(\n) end of each line.
Program Example
5. Using iter() to read and storetext file in list Python
In this example, We are iterating over the file contents using the iter() method. Also to iterate over each line of a file we are using the next() method. Then we are Appending it to empty list(list_lines) using append() method.The strip() method is used to remove newline character(\n) at end of each line.
Program Example
6. Python read text file line by line into list Python
In this example, We will use a tuple to convert a file to a list. It returns the lines of the file as a list. Let us understand this as shown in the example below.
Program Example
7. OS module to convert each line in text file into list in Python
We can use the os module fd.open() function that returns an open file object connected to file description fd. The descriptor is get by using os.open().
Program Example
9. Fileinput module to put file to list Python
In this example, we are using the fileinput module. It is used to iterate over multiple files or a list of files.
We are iterating over the file using the input() method and appending each line to list and removing new line characters using the strip() method.
Program Example
Summary :
We have explored 9 ways to conve9 ways to convert file to list in Python with code examples. Using File function, OS Module,pathlib module, Fileinput Module.
How to read a file line-by-line into a list?
How do I read every line of a file in Python and store each line as an element in a list?
I want to read the file line by line and append each line to the end of the list.
![]()
28 Answers 28
This code will read the entire file into memory and remove all whitespace characters (newlines and spaces) from the end of each line:
If you’re working with a large file, then you should instead read and process it line-by-line:
In Python 3.8 and up you can use a while loop with the walrus operator like so:
Depending on what you plan to do with your file and how it was encoded, you may also want to manually set the access mode and character encoding:
![]()
or with stripping the newline character:
![]()
![]()
This is more explicit than necessary, but does what you want.
This will yield an «array» of lines from the file.
open returns a file which can be iterated over. When you iterate over a file, you get the lines from that file. tuple can take an iterator and instantiate a tuple instance for you from the iterator that you give it. lines is a tuple created from the lines of the file.
![]()
According to Python’s Methods of File Objects, the simplest way to convert a text file into a list is:
If you just need to iterate over the text file lines, you can use:
Using with and readlines() :
If you don’t care about closing the file, this one-liner will work:
The traditional way:
![]()
If you want the \n included:
If you do not want \n included:
You could simply do the following, as has been suggested:
Note that this approach has 2 downsides:
1) You store all the lines in memory. In the general case, this is a very bad idea. The file could be very large, and you could run out of memory. Even if it’s not large, it is simply a waste of memory.
2) This does not allow processing of each line as you read them. So if you process your lines after this, it is not efficient (requires two passes rather than one).
A better approach for the general case would be the following:
Where you define your process function any way you want. For example:
(The implementation of the Superman class is left as an exercise for you).
This will work nicely for any file size and you go through your file in just 1 pass. This is typically how generic parsers will work.
![]()
Having a Text file content:
We can use this Python script in the same directory of the txt above
Using append:
Or:
Or:
Or:
![]()
Introduced in Python 3.4, pathlib has a really convenient method for reading in text from files, as follows:
(The splitlines call is what turns it from a string containing the whole contents of the file to a list of lines in the file.)
pathlib has a lot of handy conveniences in it. read_text is nice and concise, and you don’t have to worry about opening and closing the file. If all you need to do with the file is read it all in in one go, it’s a good choice.
![]()
![]()
To read a file into a list you need to do three things:
- Open the file
- Read the file
- Store the contents as list
Fortunately Python makes it very easy to do these things so the shortest way to read a file into a list is:
However I’ll add some more explanation.
Opening the file
I assume that you want to open a specific file and you don’t deal directly with a file-handle (or a file-like-handle). The most commonly used function to open a file in Python is open , it takes one mandatory argument and two optional ones in Python 2.7:
- Filename
- Mode
- Buffering (I’ll ignore this argument in this answer)
The filename should be a string that represents the path to the file. For example:
Note that the file extension needs to be specified. This is especially important for Windows users because file extensions like .txt or .doc , etc. are hidden by default when viewed in the explorer.
The second argument is the mode , it’s r by default which means «read-only». That’s exactly what you need in your case.
But in case you actually want to create a file and/or write to a file you’ll need a different argument here. There is an excellent answer if you want an overview.
For reading a file you can omit the mode or pass it in explicitly:
Both will open the file in read-only mode. In case you want to read in a binary file on Windows you need to use the mode rb :
On other platforms the ‘b’ (binary mode) is simply ignored.
Now that I’ve shown how to open the file, let’s talk about the fact that you always need to close it again. Otherwise it will keep an open file-handle to the file until the process exits (or Python garbages the file-handle).
While you could use:
That will fail to close the file when something between open and close throws an exception. You could avoid that by using a try and finally :
However Python provides context managers that have a prettier syntax (but for open it’s almost identical to the try and finally above):
The last approach is the recommended approach to open a file in Python!
Reading the file
Okay, you’ve opened the file, now how to read it?
The open function returns a file object and it supports Pythons iteration protocol. Each iteration will give you a line:
This will print each line of the file. Note however that each line will contain a newline character \n at the end (you might want to check if your Python is built with universal newlines support — otherwise you could also have \r\n on Windows or \r on Mac as newlines). If you don’t want that you can could simply remove the last character (or the last two characters on Windows):
But the last line doesn’t necessarily has a trailing newline, so one shouldn’t use that. One could check if it ends with a trailing newline and if so remove it:
But you could simply remove all whitespaces (including the \n character) from the end of the string, this will also remove all other trailing whitespaces so you have to be careful if these are important:
However if the lines end with \r\n (Windows «newlines») that .rstrip() will also take care of the \r !
Store the contents as list
Now that you know how to open the file and read it, it’s time to store the contents in a list. The simplest option would be to use the list function:
In case you want to strip the trailing newlines you could use a list comprehension instead:
Or even simpler: The .readlines() method of the file object by default returns a list of the lines:
This will also include the trailing newline characters, if you don’t want them I would recommend the [line.rstrip() for line in f] approach because it avoids keeping two lists containing all the lines in memory.
There’s an additional option to get the desired output, however it’s rather «suboptimal»: read the complete file in a string and then split on newlines:
These take care of the trailing newlines automatically because the split character isn’t included. However they are not ideal because you keep the file as string and as a list of lines in memory!