Python 如何将文本文件读入列表或数组

Python 如何将文本文件读入列表或数组

Python具有内置的文件创建、写入和读取功能。在Python中,可处理两种类型的文件:文本文件和二进制文件(用二进制语言编写,由0和1组成)。文件有6种访问模式。

要读取文本文件,我们使用 只读(’r’) 来打开一个文本文件以进行读取。句柄位于文档的开头。

有几种使用Python将文本文件读入列表或数组的方法。

使用open()方法

open() 函数从打开的文件中创建一个文件对象。文件名和模式参数会传递给 open() 函数。

示例

以下是一个示例,在该示例中使用 open() 函数以只读模式打开文件。然后,使用 read() 函数读取文件的数据。最后,使用 print() 函数打印文件的数据。

#Python program to read a text file into a list
#opening a file in read mode using open()
file = open('example.txt', 'r')

#read text file into list
data = file.read()
#printing the data of the file
print(data)

输出

执行上述程序后,将生成以下输出。

Coding encourages you to use logic and algorithms to create a program.
When facing a new challenge, you need to follow a logical approach to solve the issue.
Therefore, this is an exercise for your brain to train up your logical ability.

逻辑思维不仅仅是解决算法问题,对你的个人和职业生活也有益处。

使用numpy中的load()方法

在Python中,numpy.load()用于从文本文件中加载数据,旨在成为简单文本文件的快速读取器。文件名和模式参数传递给open()函数。

示例1

在以下示例中,从numpy模块导入loadtxt,并将文本文件读取为numpy数组。使用print()函数将数据打印到列表中。

from numpy import loadtxt

#read text file into NumPy array
data = loadtxt('example.txt')
#printing the data into the list
print(data)
print(data.dtype)

输出

在执行以上程序后,将生成以下输出。

[ 1.  2.  3.  4.  5.  6.  7.  8.  9. 10. 11. 12. 13. 14.]
Float64

loadtxt() 允许我们在导入文本文件时选择数据类型,这是 loadtxt() 的一个好功能。让我们使用一个整数来指定要导入到NumPy数组的文本文件。

示例2

在下面的示例中,从 numpy 模块中导入 loadtxt 函数。使用 loadtxt() 函数将文本文件读入NumPy数组。然后,使用 print() 函数将数据打印为列表。

from numpy import loadtxt
#read text file into NumPy array
data = loadtxt('example.txt', dtype='int')
#printing the data into the list
print(data)
print(data.dtype)

输出

执行上述程序后,将会生成以下输出。

[ 1  2  3  4  5  6  7  8  9 10 11 12 13 14]
int32

使用data.replace()方法

使用Pandas创建的数据帧。在数据帧中,replace()函数用于替换字符串、正则表达式、列表、字典、序列、数字等。由于其各种变体,这是一个非常丰富的函数。

示例

在下面的示例中,文件以只读模式打开,并使用 read() 函数进行读取。行的结尾’\n’被替换为’ ‘,如果看到更多的’.’,则会进行分割。现在,使用 print() 函数将数据打印为输出。

#program to read a text file into a list
#opening the file in read mode
file = open("example.txt", "r")
data = file.read()
# replacing end of line('/n') with ' ' and
# splitting the text it further when '.' is seen.
list = data.replace('\n', '').split(".")

# printing the data
print(list)
file.close()

输出

执行上述程序后,生成以下输出结果。

[' Coding encourages you to use logic and algorithms 
to create a program', 'When facing a new challenge, you need to follow a logical 
approach to solve the issue', 'Therefore, this is an exercise for your brain to 
train up your logical ability', ' Logical thinking is not only about solving 
algorithms but also beneficial to your personal and professional life', '']

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程