Python如何读取文件特定行

Python如何读取文件特定行

Python如何读取文件特定行

  文本文件由纯文本内容组成。文本文件也称为平面文件或纯文件。Python 为读取和访问文件中的内容提供了简单的支持。首先打开文本文件,然后按行的顺序从中访问内容。默认情况下,行号从第 0 个索引开始。

Python如何读取文件特定行
Python如何读取文件特定行

  在python中有多种方法可以从文本文件中读取特定行。之前,我们了解了Python逐行读取文件方法,本文晓得博客为你简单介绍Python如何读取文件特定行的方法。

  推荐:如何在Python中创建表格

方法一:fileobject.readlines()

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

示例:

# 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])

输出 

tenth line
 

This is line 10.

first three lines
 

This is line 1.This is line 2.This is line 3.

方法二:linecache包

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

语法: 

getLine(txt 文件,line_number)

示例:

# 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 循环结合用于数据列表中。可以通过指定数组中所需的索引号来访问特定索引处的行。 

示例:

# 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.

总结

   以上是晓得博客为介绍的Python如何读取文件特定行的全部内容,前提是了解在 Python中创建和导入自定义模块来解决实际遇到的问题。

  推荐:零基础如何开始学习Python

给文章评分

晓得博客,版权所有丨如未注明,均为原创
晓得博客 » Python如何读取文件特定行

转载请保留链接:https://www.pythonthree.com/read-specific-lines-from-a-file-in-python/

Claude、Netflix、Midjourney、ChatGPT Plus、PS、Disney、Youtube、Office 365、多邻国Plus账号购买,ChatGPT API购买,优惠码XDBK,用户购买的时候输入优惠码可以打95折

Chatgpt-Plus注册购买共享账号
滚动至顶部