Python中如何跳转到特定行?

51 投票
8 回答
112113 浏览
提问于 2025-04-15 20:26

我想在一个.txt文件中跳到第34行并读取它。你在Python中怎么做呢?

8 个回答

6

一个不会读取文件多余部分的解决方案是

from itertools import islice
line_number = 34

with open(filename) as f:
    # Adjust index since Python/islice indexes from 0 and the first 
    # line of a file is line 1
    line = next(islice(f, line_number - 1, line_number))

一个非常简单的解决方案是

line_number = 34

with open(filename) as f:
    f.readlines()[line_number - 1]
8

这段代码会打开一个文件,读取其中的一行,然后把它打印出来。

# Open and read file into buffer
f = open(file,"r")
lines = f.readlines()

# If we need to read line 33, and assign it to some variable
x = lines[33]
print(x)
106

可以使用Python标准库中的 linecache 模块:

line = linecache.getline(thefilename, 33)

这个模块正好能满足你的需求。你甚至不需要自己打开文件——linecache 会为你处理好一切!

撰写回答