转到Python中的特定行?

Arc*_*ler 40 python

我想转到.txt文件中的第34行并阅读它.你会怎么用Python做的?

Ale*_*lli 93

使用Python标准库的linecache模块:

line = linecache.getline(thefilename, 33)
Run Code Online (Sandbox Code Playgroud)

应该做你想要的.您甚至不需要打开文件 - linecache为您完成所有操作!

  • +1是一个很好的优雅解决方案,我们(或至少我)学到了新的东西. (3认同)

小智 6

此代码将打开文件,读取行并打印它.

# 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)
Run Code Online (Sandbox Code Playgroud)


Mik*_*ham 5

一个不会读取更多文件的解决方案是

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))
Run Code Online (Sandbox Code Playgroud)

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

line_number = 34

with open(filename) as f:
    f.readlines()[line_number - 1]
Run Code Online (Sandbox Code Playgroud)