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文件也可以是二进制文件的形式。这意味着我们必须改变访问文件的方法。
我们将以二进制模式读写文件,在这种情况下,模式是”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 文件内容信息的方法。
既然我们知道了CSV文件的格式,我们可以使用pandas创建一个DataFrame。
结论
在本文中,我们了解了什么是.data文件以及可以在.data文件中保存哪些类型的数据。使用open()和read()函数,我们学会了如何读取多种类型的.data文件,如文本文件和二进制文件。我们还学会了如何使用encode()函数将字符串转换为字节。