📜  如何在Python中将文本文件读入列表?

📅  最后修改于: 2022-05-13 01:54:31.419000             🧑  作者: Mango

如何在Python中将文本文件读入列表?

在本文中,我们将了解如何在Python中将文本文件读入列表。

演示文件:

示例 1:通过在出现 '.' 时拆分文本来将文本文件转换为列表。

我们以阅读模式打开文件,然后使用 read() 读取所有文本并将其存储到一个名为 data 的变量中。之后,我们将行尾('/n')替换为'',并在'.'时进一步拆分文本。使用 split() 和 replace() 函数可以看到。

read():读取的字节以字符串形式返回。读取 n 个字节,如果没有给出 n,则读取整个文件。

split(): split() 方法从字符串创建一个列表。可以指定分隔符;默认分隔符是任何空格。

replace(): replace() 方法用一个短语替换另一个短语。

代码:

Python3
# opening the file in read mode
my_file = open("file1.txt", "r")
  
# reading the file
data = my_file.read()
  
# replacing end of line('/n') with ' ' and
# splitting the text it further when '.' is seen.
data_into_list = data.replace('\n', ' ').split(".")
  
# printing the data
print(data_into_list)
my_file.close()


Python3
# opening the file in read mode
my_file = open("file1.txt", "r")
  
# reading the file
data = my_file.read()
  
# replacing end splitting the text 
# when newline ('\n') is seen.
data_into_list = data.split("\n")
print(data_into_list)
my_file.close()


输出:

['Hello geeks Welcome to geeksforgeeks']

示例 2:通过在出现换行符 ('\n' ) 处拆分文本来将文本文件转换为列表

与以前相同的过程,但我们在这里不替换任何字符串。

Python3

# opening the file in read mode
my_file = open("file1.txt", "r")
  
# reading the file
data = my_file.read()
  
# replacing end splitting the text 
# when newline ('\n') is seen.
data_into_list = data.split("\n")
print(data_into_list)
my_file.close()

输出:

['Hello geeks', 'Welcome to geeksforgeeks']