- How do I read a .data file in Python?
- What is a .data file?
- Identifying data within .data files
- Reading the .data Text File
- Algorithm (Steps)
- Example
- Output
- Reading the .data Binary File
- Algorithm (Steps)
- Example
- Output
- Conclusion
- Как читать файлы .data в Python?
- Что собой представляют файлы .data?
- Идентификация данных в файлах .data
- 1. Тестирование: текстовый файл
- 2. Тестирование: бинарный файл
- 3. Использование Pandas для чтения файлов .data
- Какие еще есть форматы для хранения данных?
- 1. Файлы JSON
- 2. Pickle
- Заключение
How do I read a .data file in Python?
In this article, we will learn what is a .data file and how to read a .data file in python.
What is a .data file?
.data files were created to store information/data.
Data in this format is frequently placed in either a comma-separated value format or a tab-separated value format.
In addition to that, the file may be in binary or text file format. In that case, we’ll have to find another way to access it.
For this tutorial, we will be working with.csv files, but first, we must determine whether the file’s content is text or binary.
Identifying data within .data files
.data files are available in two formats, with the file itself being either text or binary.
We’ll have to load it up and test it ourselves to figure out which one it belongs to.
Reading the .data Text File
.data files are generally text files, and reading files with Python is simple.
Because file handling is pre-built as a feature of Python, we don’t need to import any modules to work with it.
That being said, the following is how you open, read, and write to a file in Python −
Algorithm (Steps)
Following are the Algorithm/steps to be followed to perform the desired task. −
- Use the open() function again to open the .data file in write mode by passing the file name, and mode ‘w’ as arguments to it. If the file specified does not exist, it creates one with the given name and opens it in writing mode.
- Write some random data into the file using the write() function.
- Use the close() function to close the file after writing data into the file.
- Use the open() function(opens a file and returns a file object as a result) to open the .data file in read-only mode by passing the file name, and mode ‘r’ as arguments to it.
- Use the read() function(reads the specified number of bytes from the file and returns them. The default value is -1, which means the entire file) to read the data of the file. and print it
- Use the close() function to close the file after reading data from the file.
Example
The following program shows how to read a text .data file in Python −
# opening the .data file in write mode datafile = open("tutorialspoint.data", "w") # writing data into the file datafile.write("Hello Everyone this is tutorialsPoint. ") # closing the file datafile.close() # opening the .data file in read-only mode datafile = open("tutorialspoint.data", "r") # reading the data of the file and printing it print('The content in the file is:') print(datafile.read()) # closing the file datafile.close()
Output
The content in the file is: Hello Everyone this is tutorialsPoint.
Reading the .data Binary File
The .data files may also be in the form of binary files. This implies that we must change the method we access the file.
We’ll read and write to the file in binary mode; in this case, the mode is rb, or read binary.
That being said, the following is how you open, read, and write a file in Python −
Algorithm (Steps)
Following are the Algorithm/steps to be followed to perform the desired task. −
- Use the open() function again to open the .data file in write-binary mode by passing the same file name and mode ‘wb’ as arguments to it. If the file specified does not exist, it creates one with the given name and opens it in write binary mode.
- As we write to the binary file, we must transform the data from text to binary format, which we can do with the encode() function(The encode() method in Python is responsible for returning the encoded form of any supplied text. To efficiently store such strings, the code points are converted into a series of bytes. This is known as encoding. Python’s default encoding is utf-8).
- Write the above-encoded data into the file using the write() function.
- Use the close() function to close the file after writing the binary data into the file.
- Use the open() function(opens a file and returns a file object as a result) to open the .data file in read-binary mode by passing the file name, and mode ‘rb’ as arguments to it.
- Use the read() function(reads the specified number of bytes from the file and returns them. The default value is -1, which means the entire file) to read the data of the file and print it.
- Use the close() function to close the file after reading the binary data from the file.
Example
The following program shows how to read a binary .data file in Python −
# opening the .data file in write-binary mode datafile = open("tutorialspoint.data", "wb") # writing data in encoded format into the file datafile.write("Hello Everyone this is tutorialspoint. ".encode()) # closing the file datafile.close() # opening the .data file in read-binary mode datafile = open("tutorialspoint.data", "rb") # reading the data of the binary .data file and printing it print('The content in the file is:') print(datafile.read()) # closing the file datafile.close()
Output
The content in the file is: b'Hello Everyone this is tutorialspoint. '
File operations in Python are reasonably simple to understand and are worth exploring if you want to learn about the various file access modes and methods.
Either of these ways should work and offer you a method to get information about the contents of the .data file.
We can use pandas to create a DataFrame for the CSV file now that we know what format it is in.
Conclusion
In this article, we learned what a.data file is and what types of data can be saved in .data files. Using the open() and read() functions, we learned how to read several types of .data files, such as text files and binary files. We also learned how to use the encode() function to convert a string to Bytes.
Как читать файлы .data в Python?
При вводе и сборе данных для учебных моделей мы сталкиваемся с файлами .data. Такое расширение используется некоторыми программами. Одним из примеров является Analysis Studio, специализирующаяся на статистическом анализе и добыче данных.
Работа с расширением файла .data довольно проста и сводится к определению способа сортировки данных с последующим использованием команд Python для доступа к файлу соответствующим образом.
Что собой представляют файлы .data?
Файлы .data были разработаны как средство хранения данных. Чаще всего данные в этом формате размещаются в формате значений, разделенных запятыми или табуляцией. Наряду с этим файл может быть в текстовом формате или в двоичном. Режимы доступа для этих двух случаев будут разными.
В этой статье мы будем работать с файлами, где данные хранятся в виде значений, разделенных запятыми, но давайте сначала определим, является ли содержимое файла текстовым или двоичным.
Идентификация данных в файлах .data
Файлы .data могут быть либо в виде текста, либо в двоичном виде. Чтобы выяснить, к какому из видов относится файл, нам нужно загрузить его и проверить.
1. Тестирование: текстовый файл
Файлы .data в основном существуют в виде текстовых файлов. Доступ к файлам в Python довольно прост, для этого есть встроенный функционал. То есть вам не придется что-либо импортировать.
Открытие, чтение и запись в файл в Python выглядят следующим образом:
# Открытие файла для чтения file = open("biscuits.data", "r") # Чтение файла file.read() # Закрытие файла file.close() # Открытие файла для записи file = open("biscuits.data", "w") # Запись файла file.write("Chocolate Chip") # Закрытие файла file.close()
2. Тестирование: бинарный файл
Файлы .data могут быть также в виде двоичных файлов. При открытии таких файлов нужно поменять режим доступа. Для чтения это будет режим rb (расшифровывается как read binary) , а для записи – wb (write binary).
# Открытие и чтение бинарного файла file = open("biscuits.data", "rb") file.read() file.close() # Открытие и запись бинарного файла file = open("biscuits.data", "wb") file.write("Oreos") file.close()
Файловые операции в Python относительно просты. Попробуйте разные режимы на практике, чтобы увидеть разницу между ними.
Какой-нибудь из этих подходов должен сработать и предоставить вам метод получения информации о содержимом, хранящемся в файле .data.
Теперь, когда мы знаем, в каком формате представлен файл, мы можем поработать с pandas, чтобы создать DataFrame для файла.
3. Использование Pandas для чтения файлов .data
Простым методом извлечения информации из этих файлов после проверки типа содержимого будет использование функции read_csv() , предоставляемой Pandas.
Примечание редакции: “csv” расшифровывается как “значения, разделенные запятыми”, а “tsv”, соответственно, “значения, разделенные табуляцией”.
import pandas as pd # Чтение csv-файла data = pd.read_csv('file.data', sep=",") print(data) # Чтение tsv-файла data = pd.read_csv('otherfile.data', sep="\t") print(data)
Этот метод также автоматически преобразует данные в датафрейм.
Ниже используется пример файла csv, который был переформатирован в файл .data. Доступ к нему осуществляется с помощью того же кода, который приведен выше.
Series reference Description Period Previously published Revised 0 PPIQ.SQU900000 PPI output index - All industries 2020.06 1183 1184 1 PPIQ.SQU900001 PPI output index - All industries excl OOD 2020.06 1180 1181 2 PPIQ.SQUC76745 PPI published output commodity - Transport sup. 2020.06 1400 1603 3 PPIQ.SQUCC3100 PPI output index level 3 - Wood product manufa. 2020.06 1169 1170 4 PPIQ.SQUCC3110 PPI output index level 4 - Wood product manufa. 2020.06 1169 1170 .. . . . . . 73 PPIQ.SQNMN2100 PPI input index level 3 - Administrative and s. 2020.06 1194 1195 74 PPIQ.SQNRS211X PPI input index level 4 - Repair & maintenance 2020.06 1126 1127 75 FPIQ.SEC14 Farm expenses price index - Dairy farms - Freight 2020.06 1102 1120 76 FPIQ.SEC99 Farm expenses price index - Dairy farms - All . 2020.06 1067 1068 77 FPIQ.SEH14 Farm expenses price index - All farms - Freight 2020.06 1102 1110 [78 rows x 5 columns]
Как видите, это действительно дало нам DataFrame в качестве вывода.
Какие еще есть форматы для хранения данных?
Иногда стандартный метод хранения данных просто не подходит. Итак, каковы альтернативы работе с файловым хранилищем?
1. Файлы JSON
Как метод хранения информации, JSON – замечательная структура данных, а огромная поддержка модуля JSON в Python очень облегчает работу с этим форматом.
Однако, чтобы работать с JSON в Python, вам нужно будет импортировать модуль json.
После построения JSON-совместимой структуры ее сохранение – это простая файловая операция с json-дампами.
# Дамп структуры в форме объекта JSON в файл with open("file.json", "w") as f: json.dumps(['foo', ], f) # С помощью этого модуля также можно отсортировать ключи и организовать красивый вывод with open("file.json", "w") as f: json.dumps(['foo', ], f, indent=4, sort_keys=True)
Обратите внимание, что мы делаем сброс в файл с помощью переменной f .
Эквивалентная функция для получения информации из файла JSON называется load .
with open('file.json') as f: data = json.load(f)
Это предоставляет нам структуру и информацию об объекте JSON внутри файла.
2. Pickle
Обычно, когда вы сохраняете информацию, она хранится в формате сырых строк, в результате чего объект теряет свои свойства, и для дальнейшего использования нам приходится восстанавливать его.
Для борьбы с этой проблемой используется модуль pickle, который был создан для сериализации и десериализации объектных структур Python, чтобы их можно было хранить в файле.
Это означает, что вы можете сохранить список при помощи pickle, и когда он будет загружен модулем pickle в следующий раз, вы не потеряете ни одного из свойств объекта списка.
Для того чтобы воспользоваться этим, нам нужно импортировать модуль pickle. Устанавливать его не нужно, так как он является частью стандартной библиотеки Python.
Давайте создадим словарь для работы со всеми нашими файловыми операциями.
apple = banana = orange = fruitShop = <> fruitShop["apple"] = apple fruitShop["banana"] = banana fruitShop["orange"] = orange
Работать с модулем pickle так же просто, как и с JSON.
file = open('fruitPickles', 'ab') # Режим 'ab' позволяет открывать # для дозаписи файл в бинарном формате # Метод dump добавляет данные в файл # в безопасном сериализованном формате. pickle.dump(fruitShop, file) file.close() file = open('fruitPickles', 'rb') # Теперь мы можем читать из файла при помощи функции load. fruitShop = pickle.load(file) file.close()
Заключение
Теперь вы знаете, что такое файлы .data и как с ними работать. Наряду с этим вы также познакомились с другими доступными вариантами хранения и получения данных.