如何在Python中读取.data文件?
在本文中,我们将学习什么是.data文件以及如何在python中读取.data文件。
什么是.data文件?
.data文件用于存储信息/数据。
此格式的数据通常以逗号分隔值格式或制表符分隔值格式存储。
此外,文件可能为二进制或文本文件格式。在这种情况下,我们将需要找到另一种访问方式。
在本教程中,我们将使用.csv文件,但首先,我们必须确定文件内容是文本还是二进制。
识别.data文件中的数据
.data文件有两种格式,文件本身可以是文本或二进制。
我们将不得不加载并测试它来确定它属于哪一种。
读取.data文本文件
.data文件通常是文本文件,在Python中读取文件很简单。
因为文件处理是Python的内置功能,所以我们不需要导入任何模块来处理它。
也就是说,以下是你在Python中打开、读取和写入文件的方法:
算法(步骤)
以下是执行所需任务的算法/步骤:
再次使用open()函数以写入模式打开.data文件,将文件名和模式‘w’作为参数传递给它。如果指定的文件不存在,则创建一个具有给定名称的文件并以写入模式打开它。
使用write()函数将一些随机数据写入文件。
写入数据后,使用close()函数关闭文件。
使用open()函数(打开文件并返回文件对象)以只读模式打开.data文件,将文件名和模式‘r’作为参数传递给它。
使用read()函数(读取文件中指定数量的字节并返回它们。默认值为-1,这意味着整个文件)读取文件数据并打印它。
读取文件数据后,使用close()函数关闭文件。
示例
以下程序演示如何在Python中读取.data文本文件:
# 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()
输出
The content in the file is: Hello Everyone this is tutorialsPoint!!!
读取.data二进制文件
.data文件也可能是二进制文件。这意味着我们必须更改访问文件的方法。
我们将以二进制模式读取和写入文件;在这种情况下,模式为rb,即读取二进制。
也就是说,以下是你在Python中打开、读取和写入文件的方法:
算法(步骤)
以下是执行所需任务的算法/步骤:
再次使用open()函数以二进制写入模式打开.data文件,传递相同的文件名和模式‘wb’作为参数。如果指定的文件不存在,则创建一个具有给定名称的文件并以二进制写入模式打开它。
当我们写入二进制文件时,我们必须将数据从文本转换为二进制格式,我们可以使用encode()函数(Python中的encode()方法负责返回任何提供的文本的编码形式。为了有效地存储这些字符串,代码点被转换为一系列字节。这被称为编码。Python的默认编码是utf-8)。
使用write()函数将上述编码后的数据写入文件。
写入二进制数据后,使用close()函数关闭文件。
使用open()函数(打开文件并返回文件对象)以二进制读取模式打开.data文件,将文件名和模式‘rb’作为参数传递给它。
使用read()函数(读取文件中指定数量的字节并返回它们。默认值为-1,这意味着整个文件)读取文件数据并打印它。
读取二进制数据后,使用close()函数关闭文件。
示例
以下程序演示如何在Python中读取.data二进制文件:
# 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()
输出
The content in the file is: b'Hello Everyone this is tutorialspoint!!!'
Python中的文件操作相当容易理解,如果你想了解各种文件访问模式和方法,值得探索。
这两种方法都可以工作,并为你提供获取.data文件内容信息的方法。
现在我们知道它是哪种格式了,我们可以使用pandas为CSV文件创建一个DataFrame。
结论
在本文中,我们学习了什么是.data文件以及.data文件中可以保存哪些类型的数据。使用open()和read()函数,我们学习了如何读取几种类型的.data文件,例如文本文件和二进制文件。我们还学习了如何使用encode()函数将字符串转换为字节。
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP