📜  如何从Python中的文件中读取特定行?

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

如何从Python中的文件中读取特定行?

文本文件由纯文本内容组成。文本文件也称为平面文件或纯文件。 Python为读取和访问文件中的内容提供了简单的支持。首先打开文本文件,然后按行的顺序从中访问内容。默认情况下,行号从第 0 个索引开始。在Python中有多种方法可以从文本文件中读取特定行,本文旨在讨论它们。

正在使用的文件: test.txt

方法一:fileobject.readlines()

可以在Python中创建一个文件对象,然后可以在该对象上调用 readlines() 方法以将行读取到流中。当需要同时访问文件中的一行或一系列行时,首选此方法。它可以很容易地用于打印从任何随机起始索引到某个结束索引的行。它最初读取文件的全部内容并将其副本保存在内存中。然后访问指定索引处的行。

例子:

Python3
# open the sample file used
file = open('test.txt')
  
# read the content of the file opened
content = file.readlines()
  
# read 10th line from the file
print("tenth line")
print(content[9])
  
# print first 3 lines of file
print("first three lines")
print(content[0:3])


Python3
# importing required package
import linecache
  
# extracting the 5th line
particular_line = linecache.getline('test.txt', 4)
  
# print the particular line
print(particular_line)


Python3
# open a file
file = open("test.txt")
  
# lines to print
specified_lines = [0, 7, 11]
  
# loop over lines in a file
for pos, l_num in enumerate(file):
    # check if the line number is specified in the lines to read array
    if pos in specified_lines:
        # print the required line number
        print(l_num)


输出

方法二:linecache包

linecache 包可以在Python中导入,然后用于提取和访问Python中的特定行。该包可用于同时读取多行。它利用缓存存储在内部执行优化。这个包自己打开文件并到达特定的行。这个包有用于相同的 getline() 方法。

句法:

getLine(txt-file, line_number)

例子:

蟒蛇3

# importing required package
import linecache
  
# extracting the 5th line
particular_line = linecache.getline('test.txt', 4)
  
# print the particular line
print(particular_line)

输出 :

This is line 5.

方法三:enumerate()

enumerate() 方法用于将字符串或列表对象转换为由数字索引的数据序列。然后将其与 for 循环结合用于数据列表中。可以通过指定数组中所需的索引号来访问特定索引处的行。

例子:

蟒蛇3

# open a file
file = open("test.txt")
  
# lines to print
specified_lines = [0, 7, 11]
  
# loop over lines in a file
for pos, l_num in enumerate(file):
    # check if the line number is specified in the lines to read array
    if pos in specified_lines:
        # print the required line number
        print(l_num)

输出

This is line 1.
This is line 8.
This is line 12.