如何在 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 文件 -

扫描二维码关注公众号,回复: 15333505 查看本文章
# 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() 函数以 write-binary 模式打开 .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 文件创建数据帧,现在我们知道它的格式是什么。

猜你喜欢

转载自blog.csdn.net/2301_78064339/article/details/131007304